在JAVA中,用synchronized关键字用于确保多个线程不会同时执行某个方法或代码块,从而防止并发问题,C#中有多中方法来处理这种情况。
Lock语句
lock语句是最常用的同步机制,类似于JAVA的synchronized。他使用一个对象作为锁,确保同一个时间只有一个线程可以进入被锁定的代码块。示例如下。
using System;
using System.Threading;
class Program
{
private static readonly object _lock = new object();
private static int _counter = 0;
static void Main()
{
Thread thread1 = new Thread(IncrementCounter);
Thread thread2 = new Thread(IncrementCounter);
thread1.Start();
thread2.Start();
thread1.Join();
thread2.Join();
Console.WriteLine($"Final counter value: {_counter}");
}
static void IncrementCounter()
{
for (int i = 0; i < 1000; i++)
{
lock (_lock)
{
_counter++;
}
}
}
}
Monitor类
monitor提供了更细粒度的控制,允许手动进入临界区。lock语句实际是monitor的一个简化版本。monitor示例如下。
using System;
using System.Threading;
class Program
{
private static readonly object _lock = new object();
private static int _counter = 0;
static void Main()
{
Thread thread1 = new Thread(IncrementCounter);
Thread thread2 = new Thread(IncrementCounter);
thread1.Start();
thread2.Start();
thread1.Join();
thread2.Join();
C