AutoResetEvent 事件锁
作者:互联网
案例学习笔记
class AutoResetEventTest
{
const int numIterations = 10;
static AutoResetEvent myResetEvent = new AutoResetEvent(false);
static AutoResetEvent ChangeEvent = new AutoResetEvent(false);
//static ManualResetEvent myResetEvent = new ManualResetEvent(false);
//static ManualResetEvent ChangeEvent = new ManualResetEvent(false);
static int number; //这是关键资源
static void Main()
{
Thread payMoneyThread = new Thread(new ThreadStart(PayMoneyProc));
payMoneyThread.Name = "付钱线程";
Thread getBookThread = new Thread(new ThreadStart(GetBookProc));
getBookThread.Name = "取书线程";
payMoneyThread.Start();
getBookThread.Start();
for (int i = 1; i <= numIterations; i++)
{
Console.WriteLine("买书线程:数量{0}", i);
number = i;
//Signal that a value has been written.
myResetEvent.Set();//通知线程
ChangeEvent.Set();
Thread.Sleep(100);
Console.WriteLine("------------------------------------------");
}
payMoneyThread.Abort();
getBookThread.Abort();
Console.ReadKey();
}
static void PayMoneyProc()
{
while (true)
{
myResetEvent.WaitOne();
//myResetEvent.Reset();
Console.WriteLine("{0}:数量{1}", Thread.CurrentThread.Name, number);
}
}
static void GetBookProc()
{
while (true)
{
ChangeEvent.WaitOne();
// ChangeEvent.Reset();
Console.WriteLine("{0}:数量{1}", Thread.CurrentThread.Name, number);
Thread.Sleep(0);
}
}
}
标签:false,Thread,AutoResetEvent,ManualResetEvent,static,事件,new 来源: https://www.cnblogs.com/wml-it/p/16424525.html