在《使用lock語句同步多個線程》的文章中,使用lock語句同步多線程訪問臨界資源。
使用lock語句的代碼如下所示。
private static object o = new object(); lock (o) { if (account >= 1000) { Thread.Sleep(10);//自動取款機打了個小盹 account -= 1000; pocket += 1000; } }
使用ILDASM工具查看上面代碼對應的IL代碼:
<喎?http://www.Bkjia.com/kf/ware/vc/" target="_blank" class="keylink">vcD4KPHA+v8nS1Leiz9ajumxvY2vT777ksbu94s72zqq199PDTW9uaXRvcsDgtcRFbnRlcigpt723qLrNRXhpdCgpt723qKGjPC9wPgo8cD7PwsPmvs3AtL3pydzSu8/CTW9uaXRvcsDgysfI57rOvfjQ0Lbgz9+zzM2ssr21xKGjPC9wPgo8cD6199PDTW9uaXRvcsDgtcRFbnRlcigpt723qL/J0tS78cihwdm959fK1LS1xLbA1bzL+KO7tvi199PDTW9uaXRvcsDgtcRFeGl0KCm3vbeou+HKzbfFtsDVvMv4o6zNy7P2wdm958f4oaO1sdK7uPbP37PMyrnTw7bA1bzL+LXEt73KvbfDzsrXytS0yrGjrMbky/vP37PMvs2yu8Tct8POyrjD18rUtKGjy/nS1Mq508NNb25pdG9ywOC1xEVudGVyKCm3vbeous1FeGl0KCm3vbeov8nS1Mi3saPDv7TO1rvT0NK7uPbP37PMt8POysHZvefXytS0o6zS1LTvtb3NrLK9tuC49s/fs8y1xMS/tcShozwvcD4KPHA+z8LD5sq508NNb25pdG9ywOC4xNC0obbKudPDbG9ja9PvvuTNrLK9tuC49s/fs8yht9K7zsS1xMq+wP2zzNDyoaM8L3A+CjxwPjxwcmUgY2xhc3M9"brush:java;">using System; using System.Threading; namespace MonitorExample { class Program { static object o = new object(); static int account = 1000;//賬戶 static int pocket = 0;//口袋 static void Main(string[] args) { int threadCount = 10; var threads = new Thread[threadCount]; for (int i = 0; i < threadCount; i++) { threads[i] = new Thread(DoSafeWork); threads[i].Start(); } for (int i = 0; i < threadCount; i++) { threads[i].Join(); } Console.WriteLine("pocket=" + pocket); } public static void DoSafeWork() { Monitor.Enter(o); try { if (account >= 1000) { Thread.Sleep(10);//自動取款機打了個小盹 account -= 1000; pocket += 1000; } } finally { Monitor.Exit(o); } } } }程序執行結果如下圖所示。