using System;
using System.Threading;
namespace LockTest
{
class Account
{
private object thisLock = new object();
double balance;
Random r = new Random();
public int number = 0;
public Account(double Initial)
{
balance = Initial;
}
double WithDraw(double amount)
{
if (balance < 0)
throw new Exception("余额为负");
lock (thisLock)
{
if (balance >= amount)
{
number++;
Console.WriteLine("number:" + number);
Console.WriteLine("取款前余额:{0}", balance);
Console.WriteLine("取款:{0}:", amount);
balance -= amount;
Console.WriteLine("取款后余额:{0}\n", balance);
return amount;
}
else
{
Console.WriteLine("余额不足");
return 0;
}
}
}
public void DoTransactions()
{
int num = 6;
for (int i = 0; i < num; i++) //当num>=6时出现问题,没有打印"number:1",但num=1-5时是正常的。
{
WithDraw(r.Next(1, 100));
}
}
}
class Program
{
static void Main(string[] args)
{
Thread[] threads = new Thread[10];
Account acc = new Account(10000);
for (int i = 0; i < 10; i++)
{
Thread t = new Thread(new ThreadStart(acc.DoTransactions));
threads[i]=t;
threads[i].Start();
}
//for (int i = 0; i < 10; i++)
//{
// threads[i].Start();
//}
}
}
}
i < num ,而 num = 6
num > = 6 时, 退出 for 循环,WithDraw(r.Next(1, 100)); 就不执行了.
我把你的代码运行了一下,没有任何问题,即使把num改成26也没有问题啊,不会出现你说的那种情况,你再试一下,是不是看错了