同步对象 AutoResetEvent
操作:waitone() 阻塞当前线程,等待接收信号量。是线程中wait操作,会阻塞当前线程,不占用cpu资源,同时会释放上面的锁资源。
set() 发出信号量。
namespace CaryAREDemo { class Me { const int numIterations = 550; 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(0); } payMoneyThread.Abort(); getBookThread.Abort(); } 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); Console.WriteLine("------------------------------------------"); Thread.Sleep(0); } } } }
autoResetEvent:通知等待线程事件已经触发。 每次都能重制信号量的初始值。
waitone:阻塞当前线程,直到接收到信号量。
set:会设置为终止状态(不会阻塞),因为是autoreset,等下次再用的是重置为非终止状态。
而 manualRestEvent 每次set之后,会设置为终止状态,所以不会阻塞程序,可以调用reset搞定。