日期:2009-06-26 浏览次数:20444 次
//设定优先级为最低 myThread.Priority=ThreadPriority.Lowest; |
lock(expression) statement_block |
//lock.cs using System; using System.Threading; internal class Account { int balance; Random r = new Random(); internal Account(int initial) { balance = initial; } internal int Withdraw(int amount) { if (balance < 0) { file://如果balance小于0则抛出异常 throw new Exception("Negative Balance"); } //下面的代码保证在当前线程修改balance的值完成之前 //不会有其他线程也执行这段代码来修改balance的值 //因此,balance的值是不可能小于0的 lock (this) { Console.WriteLine("Current Thread:"+Thread.CurrentThread.Name); file://如果没有lock关键字的保护,那么可能在执行完if的条件判断之后 file://另外一个线程却执行了balance=balance-amount修改了balance的值 file://而这个修改对这个线程是不可见的,所以可能导致这时if的条件已经不成立了 file://但是,这个线程却继续执行balance=balance-amount,所以导致balance可能小于0 if (balance >= amount) { Thread.Sleep(5); balance = balance - amount; return amount; } else { return 0; // transaction rejected } } } internal void DoTransactions() { for (int i = 0; i < 100; i++) Withdraw(r.Next(-50, 100)); } } internal class Test { static internal Thread[] threads = new Thread[10]; public static void Main() { Account acc = new Account (0); for (int i = 0; i < 10; i++) { Thread t = new Thread(new ThreadStart(acc.DoTransactions)); threads[i] = t; } for (int i = 0; i < 10; i++) threads[i].Name=i.ToString(); for (int i = 0; i < 10
免责声明: 本文仅代表作者个人观点,与爱易网无关。其原创性以及文中陈述文字和内容未经本站证实,对本文以及其中全部或者部分内容、文字的真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
相关资料更多> |