一个线程中lock用法的经典实例

时间:2023-03-09 18:00:20
一个线程中lock用法的经典实例
 /*
该实例是一个线程中lock用法的经典实例,使得到的balance不会为负数
同时初始化十个线程,启动十个,但由于加锁,能够启动调用WithDraw方法的可能只能是其中几个
作者:http://hi.baidu.com/jiang_yy_jiang
*/
using System; namespace ThreadTest29
{
class Account
{
private Object thisLock = new object();
int balance;
Random r = new Random(); public Account(int initial)
{
balance = initial;
} int WithDraw(int amount)
{
if (balance < )
{
throw new Exception("负的Balance.");
}
//确保只有一个线程使用资源,一个进入临界状态,使用对象互斥锁,10个启动了的线程不能全部执行该方法
lock (thisLock)
{
if (balance >= amount)
{
Console.WriteLine("----------------------------:" + System.Threading.Thread.CurrentThread.Name + "---------------"); Console.WriteLine("调用Withdrawal之前的Balance:" + balance);
Console.WriteLine("把Amount输入 Withdrawal :-" + amount);
//如果没有加对象互斥锁,则可能10个线程都执行下面的减法,加减法所耗时间片段非常小,可能多个线程同时执行,出现负数。
balance = balance - amount;
Console.WriteLine("调用Withdrawal之后的Balance :" + balance);
return amount;
}
else
{
//最终结果
return ;
}
}
}
public void DoTransactions()
{
for (int i = ; i < ; i++)
{
//生成balance的被减数amount的随机数
WithDraw(r.Next(, ));
}
}
} class Test
{
static void Main(string[] args)
{
//初始化10个线程
System.Threading.Thread[] threads = new System.Threading.Thread[];
//把balance初始化设定为1000
Account acc = new Account();
for (int i = ; i < ; i++)
{
System.Threading.Thread t = new System.Threading.Thread(new System.Threading.ThreadStart(acc.DoTransactions));
threads[i] = t;
threads[i].Name = "Thread" + i.ToString();
}
for (int i = ; i < ; i++)
{
threads[i].Start();
}
Console.ReadKey();
}
}
}