模擬10個線程,每個線程模擬100次取錢:
其實就是相當於1000個人來同時取錢。當然實際情況是取錢的人分佈在不同的地區的取款機取錢。同一個取款機只能一個人操作。
關鍵是要保證取錢的餘額要準確,不能在多人同時操作的時候計算失誤,於是要在計算餘額的時候鎖住。lock關鍵作用在於此。
static void test() { //初始化10個線程 System.Threading.Thread[] threads = new System.Threading.Thread[10]; //把balance初始化設定爲1000 Account acc = new Account(1000); for (int i = 0; i < 10; i++) { System.Threading.Thread t = new System.Threading.Thread(new System.Threading.ThreadStart(acc.DoTransactions)); threads[i] = t; threads[i].Name = "Thread" + i.ToString(); } for (int i = 0; i < 10; i++) { threads[i].Start(); } } public class Account { private Object thisLock = new object(); int balance; Random r = new Random(); public Account(int initial) { balance = initial; } int WithDraw(int amount) { if (balance <= 0) { Console.WriteLine("no Balance........."); return balance; } //確保只有一個線程使用資源,一個進入臨界狀態,使用對象互斥鎖,10個啓動了的線程不能全部執行該方法 lock (thisLock) { if (balance >= amount) { Console.WriteLine("----------------------------:" + System.Threading.Thread.CurrentThread.Name + "---------------"); Console.WriteLine("調用Withdrawal之前的Balance:" + balance); Console.WriteLine("把Amount輸入 Withdrawal :-" + amount); //如果沒有加對象互斥鎖,則可能10個線程都執行下面的減法,加減法所耗時間片段非常小,可能多個線程同時執行,出現負數。 balance = balance - amount; Console.WriteLine("調用Withdrawal之後的Balance :" + balance); } else { Console.WriteLine("balance too low :"+balance +"------------>you want amount:"+ amount ); //最終結果 } return balance; } } public void DoTransactions() { for (int i = 0; i < 100; i++) { //生成balance的被減數amount的隨機數 var balance= WithDraw(r.Next(1, 100)); if (balance <= 0) { break; } } } }