📄 lock.cs
字号:
using System;
using System.Threading;
internal class Account
{
int balance;
Random r = new Random();
internal Account(int initial)
{
balance = initial;
}
internal int Withdraw(int amount)
{
if (balance < 0)
{
throw new Exception("Negative Balance");
}
// 试试注释掉lock看看有什么情况发生
lock (this)
{
Console.WriteLine("Current Thread:"+Thread.CurrentThread.Name);
if (balance >= amount)
{
Thread.Sleep(5);
balance = balance - amount;
return amount;
}
else
{
return 0;
}
}
}
internal void DoTransactions()
{
for (int i = 0; i < 100; i++)
{
Withdraw(r.Next(-50, 100));
}
}
}
internal class Test
{
static internal Thread[] threads = new Thread[10];
public static void Main()
{
Account acc = new Account (0);
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].Name=i.ToString();
}
for (int i = 0; i < 10; i++)
{
threads[i].Start();
}
Console.ReadLine();
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -