lock 关键字将语句块标记为临界区,方法是获取给定对象的互斥锁,执行语句,然后释放该锁。
class Program
{
static void Main(string[] args)
{
Thread t = new Thread(LockObject.MonitorIncrement);
Thread t1=new Thread(new ThreadStart(LockObject.LockIncrement));
t.Start();
t1.Start();
}
} public class LockObject
{
/// <summary>
/// 多线程共享数据
/// </summary>
private static int counter = ;
/// <summary>
/// 同步对象,推荐这种写法
/// 应避免锁定 public 类型,否则实例将超出代码的控制范围
/// 具体如:lock (this)、lock (typeof (MyType)) 和 lock ("myLock")
/// </summary>
private readonly static object synisynchronize = new object(); public static void MonitorIncrement()
{
///Monitor.Enter 与 Monitor.Exit 相当于Lock
Monitor.Enter(synisynchronize);
Thread.Sleep();
counter++;
Console.WriteLine("MonitorIncrement counter={0}", counter);
Monitor.Exit(synisynchronize);
} public static void LockIncrement()
{
///lock在开始时调用 Monitor.Enter
///在结束时调用 Monitor.Exit 。
lock (synisynchronize)
{
counter++;
Console.WriteLine("LockIncrement counter={0}" ,counter);
}
}
}
运行结果如下图示:
aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAAARQAAABkCAIAAADIR1hbAAAIeElEQVR4nO2cz4scRRTH+y8IAX/kGEEPxpuIuIEQDEoYs/gjCUJYTRbESAQlLuwuao5GMEFy8KAgySHx4EVByCEkspvZzB/hMYGcAx5FD+NhQ6e33o969bp6q6fn+6EJvdVVr15Vv8/2zO5sqgf3H45nlq2Bcm+4TAZEBXl6SOkK75DSBZ8TyNNHSld4h5Qu+Jww8ty9e/fW7Y1bdzYjx+2Nzc3NIs7UlC7yrihd4R1SuuBzwshz7PzV187fOrTy56GVO/Q4srbx+urGkfXNN1f+WPz8pxu//lZEm21KF3lXlK7wDild8Dlh5Nl/4a993/+97/Ijejx76dEHN/999/f/lm/+8+OVXw5+eP3k2QtFtNmmdJF3RekK75DSBZ8TRp63v77x8tIXr5xeZ4+Dy+sLy+sHl9ePnPnspfcuHl1alSp7z969zUPXgO0TRGiGoo1bW1tSf9qzCW3XByqN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