关于lock的一些疑问
小Fan 2011-04-24 03:53:07 以下是MSDN文档里面的代码,
说用了lock锁住了,balance永远不会小于0,为什么呢?
意思是不是说,只执行lock大括号里面的代码,那个 if (balance < 0)就不执行了?
请知道的人解释清楚一下,非常感谢
using System;
using System.Threading;
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)
{
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("Balance before Withdraw1: " + balance);
Console.WriteLine("Amount to Withdraw : " + amount);
balance = balance - amount;
Console.WriteLine("Balance after Withdrawal : " + balance);
return amount;
}
else
{
return 0;
}
}
}
public void DoTransactions()
{
for (int i = 0; i < 100; i++)
Withdraw(r.Next(1,100));
}
}
class Text
{
static void Main()
{
Thread[] threads = new Thread[10];
Account acc = new Account(100);
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].Start();
}//此处用2个循环,我把 threads[i].Start();放在第一个循环里面,运行结果也一样,我觉得好像没多大区别
Console.Read();
}
}