Lock关键字用于将指定对象进行锁定,防止其他线程对此对象进行访问操作,直到代码块内的语句执行完毕,然后释放该锁。
1 Object thisLock = new Object(); 2 lock (thisLock) 3 { 4 // Critical code section. 5 }
如以下多线程对同一对象进行操作的代码中lock语句被注释了,那么运行结果将会显示各线程之间进行了交叉操作,所以也非常容易抛出异常。但是添加了lock语句将会使代码执行时间增长,因为多了线程间的等待,所以还是要根据需要来进行使用。


1 using System; 2 using System.Threading; 3 4 class Account 5 { 6 private Object thisLock = new Object(); 7 int balance; 8 9 Random r = new Random(); 10 11 public Account(int initial) 12 { 13 balance = initial; 14 } 15 16 int Withdraw(int amount) 17 { 18 19 // This condition will never be true unless the lock statement 20 // is commented out: 21 if (balance < 0) 22 { 23 throw new Exception("Negative Balance"); 24 } 25 26 // Comment out the next line to see the effect of leaving out 27 // the lock keyword: 28 lock (thisLock) 29 { 30 if (balance >= amount) 31 { 32 Console.WriteLine("Balance before Withdrawal : " + balance); 33 Console.WriteLine("Amount to Withdraw : -" + amount); 34 balance = balance - amount; 35 Console.WriteLine("Balance after Withdrawal : " + balance); 36 return amount; 37 } 38 else 39 { 40 return 0; // transaction rejected 41 } 42 } 43 } 44 45 public void DoTransactions() 46 { 47 for (int i = 0; i < 100; i++) 48 { 49 Withdraw(r.Next(1, 100)); 50 } 51 } 52 } 53 54 class LockCode 55 { 56 static void Main() 57 { 58 Thread[] threads = new Thread[10]; 59 Account acc = new Account(1000); 60 for (int i = 0; i < 10; i++) 61 { 62 Thread t = new Thread(new ThreadStart(acc.DoTransactions)); 63 threads[i] = t; 64 } 65 for (int i = 0; i < 10; i++) 66 { 67 threads[i].Start(); 68 } 69 } 70 }
如果将上面代码改为对多个对象进行操作,不管加不加lock语句,自然对结果都不产生影响的。
1 static void Main() 2 { 3 Thread[] threads = new Thread[10]; 4 Account[] accArr = new Account[10]; 5 6 for (int i = 0; i < 10; i++) 7 { 8 accArr[i] = new Account(1000); 9 Thread t = new Thread(accArr[i].DoTransactions); 10 t.Start("Thread " + i); 11 } 12 }
参考:
http://msdn.microsoft.com/zh-cn/library/c5kehkcz(v=vs.90).aspx