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 = 0;/// <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(1000);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);}}}
运行结果如下图示: