【转】C#线程同步示例
using System;
using System.Threading;
// 银行帐户类
class Account
{
int balance; // 余额
Random r = new Random();
public Account(int initial)
{
balance = initial;
}
// 取钱
int Withdraw(int amount)
{
if (balance < 0)
{
throw new Exception("余额为负!");
}
lock (this)
{
if (balance >= amount)
{
Console.WriteLine("原有余额: " + balance);
Console.WriteLine("支取金额: -" + amount);
balance = balance - amount;
Console.WriteLine("现有余额: " + balance);
return amount;
}
else
{
return 0; // 拒绝交易
}
}
}
// 测试交易
public void DoTransactions()
{
// 支取随机的金额100次
for (int i = 0; i < 100; i++)
{
Withdraw(r.Next(1, 100));
}
}
}
class TestApp
{
public static void Main()
{
// 建立10个线程同时进行交易
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));
threads[i] = t;
}
for (int i = 0; i < 10; i++)
{
threads[i].Start();
}
}
}
浙公网安备 33010602011771号