标签:
class Program { static void Main(string[] args) { Thread[] threads = new Thread[10]; Account acc = new Account(1000); for (int i = 0; i < 10; i++) { Thread t = new Thread(new ThreadStart(acc.DoTransactions)); t.Name = "Thread" + i; threads[i] = t; } for (int i = 0; i < 10; i++) { threads[i].Start(); } Console.ReadKey(); } } class Account { private Object thisLock = new Object(); int balance; Random r = new Random(); public Account(int initial) { balance = initial; } int Withdraw(int amount) { // This condition will never be true unless the lock statement // is commented out: if (balance < 0) { throw new Exception("Negative Balance"); } // Comment out the next line to see the effect of leaving out // the lock keyword: lock (thisLock) { if (balance >= amount) { Console.WriteLine(Thread.CurrentThread.Name + ":,扣款前金额:" + balance); Console.WriteLine("扣款金额:" + amount); balance = balance - amount; Console.WriteLine("-------扣款后金额:" + balance); return amount; } else { return 0; // transaction rejected } } } public void DoTransactions() { for (int i = 0; i < 1000; i++) { Withdraw(r.Next(1, 10)); } } }
标签:
原文地址:http://www.cnblogs.com/AlbertJoey/p/4896882.html