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();
//}
}
}
}
ABOUTYOU
婷婷同学_
料青山看我应如是
翻阅古今