.NET中的lock(C#版本)
|
|
lock是什么.
1 public class ThreadTest
2 { 3 private int i = 0; 4 public void Test() 5 { 6 Thread t1 = new Thread(Thread1); 7 Thread t2 = new Thread(Thread2); 8 t1.Start(); 9 t2.Start(); 10 } 11 public void Thread1() 12 { 13 lock (this) 14 { 15 Console.WriteLine(this.i); 16 Thread.Sleep(1000); 17 Console.WriteLine(this.i); 18 } 19 } 20 public void Thread2() 21 { 22 Thread.Sleep(500); 23 this.i = 1; 24 Console.WriteLine("Change the value in locking"); 25 } 26 } 27 public class ThreadTest2 28 { 29 private int i = 0; 30 public void Test() 31 { 32 Thread t1 = new Thread(Thread1); 33 Thread t2 = new Thread(Thread2); 34 t1.Start(); 35 t2.Start(); 36 } 37 public void Thread1() 38 { 39 lock (this) 40 { 41 Console.WriteLine(this.i); 42 Thread.Sleep(1000); 43 Console.WriteLine(this.i); 44 } 45 } 46 public void Thread2() 47 { 48 lock (this) 49 { 50 Thread.Sleep(500); 51 this.i = 1; 52 Console.WriteLine("Can't change the value in locking"); 53 } 54 } 55 } 两段程序有什么区别吗?看看吧,ThreadTest2.Thread2()中多了一个lock(this)却产生了不同的结果 本想在案例一中lock住this对象,让其他的线程不能操作,可是事情不是像我们想象的那样lock(this)是lock this的意思.this中的属性依然能够被别的线程改变.那我们lock住的是什么?是代码段,是lock后面大括号中代码段,这段代码让多个人执行不不被允许的.那返回头来在看lock(this),this是什么意思呢?可以说this知识这段代码域的标志,看看案例二中Thread2.Thread2就明白了,Thread2中的lock需要等到Thread1种lock释放后才开始运行,释放之前一直处于等待状态,这就是标志的表现. |