C#基础概念之Lock
lock 关键字将语句块标记为临界区,方法是获取给定对象的互斥锁,执行语句,然后释放该锁。
1 class Program
2 {
3 static void Main(string[] args)
4 {
5 Thread t = new Thread(LockObject.MonitorIncrement);
6 Thread t1=new Thread(new ThreadStart(LockObject.LockIncrement));
7 t.Start();
8 t1.Start();
9 }
10 }
11
12
13 public class LockObject
14 {
15 /// <summary>
16 /// 多线程共享数据
17 /// </summary>
18 private static int counter = 0;
19 /// <summary>
20 /// 同步对象,推荐这种写法
21 /// 应避免锁定 public 类型,否则实例将超出代码的控制范围
22 /// 具体如:lock (this)、lock (typeof (MyType)) 和 lock ("myLock")
23 /// </summary>
24 private readonly static object synisynchronize = new object();
25
26 public static void MonitorIncrement()
27 {
28 ///Monitor.Enter 与 Monitor.Exit 相当于Lock
29 Monitor.Enter(synisynchronize);
30 Thread.Sleep(1000);
31 counter++;
32 Console.WriteLine("MonitorIncrement counter={0}", counter);
33 Monitor.Exit(synisynchronize);
34 }
35
36 public static void LockIncrement()
37 {
38 ///lock在开始时调用 Monitor.Enter
39 ///在结束时调用 Monitor.Exit 。
40 lock (synisynchronize)
41 {
42 counter++;
43 Console.WriteLine("LockIncrement counter={0}" ,counter);
44 }
45 }
46 }
运行结果如下图示: