📄 class1.cs
字号:
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("{0}取出的数额:{1}",Thread.CurrentThread.Name,amount);
balance = balance - amount;
Console.WriteLine("取后的存款额:" + balance);
return amount;
}
else
{
Console.WriteLine("{0}要取出的数额:{1},被拒绝",Thread.CurrentThread.Name,amount);
return 0; // 拒绝交易
}
}
}
public void DoTransactions()
{
for (int i = 0; i < 5; i++)
{
Withdraw(r.Next(1, 1000));//取款
}
}
}
class Test
{
public static void Main()
{
Thread[] threads = new Thread[3];
Account acc = new Account(1000);
for(int i = 0; i <3; i++)
{
threads[i]= new Thread(new ThreadStart(acc.DoTransactions));
threads[i].Name="Thread"+(i+1);
}
for(int i = 0; i < 3; i++)
{
threads[i].Start();
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -