在C#中,沒有像Java那樣的synchronized關鍵字
以下是一個簡單的示例,展示了如何在C#中使用lock語句:
using System;
using System.Threading;
class Program
{
private static readonly object _lockObject = new object();
public static void Main()
{
Thread thread1 = new Thread(DoWork);
Thread thread2 = new Thread(DoWork);
thread1.Start();
thread2.Start();
thread1.Join();
thread2.Join();
Console.WriteLine("Finished.");
}
private static void DoWork()
{
lock (_lockObject)
{
for (int i = 0; i < 5; i++)
{
Console.WriteLine($"Thread {Thread.CurrentThread.ManagedThreadId} is working...");
Thread.Sleep(1000);
}
}
}
}
在這個示例中,我們創建了兩個線程,它們都調用DoWork方法。DoWork方法中的lock語句確保同一時間只有一個線程可以訪問該代碼塊。這樣可以防止多個線程同時訪問共享資源(在本例中為控制臺),從而避免潛在的數據不一致和競爭條件。