AutoResetEvent
1. For blocking and releasing threads on multiple threads
StaticAutoResetEvent Auth0 =NewAutoResetEvent (false);StaticAutoResetEvent auth1 =NewAutoResetEvent (false);Static voidMain (string[] args) {Thread th=NewThread (t0); Th. IsBackground=true; Th. Start (); Thread Th1=NewThread (t1); Th1. IsBackground=true; Th1. Start (); Console.ReadLine (); }Static voidT0 () {Console.WriteLine ("1"); Auth1. Set (); Auth0. WaitOne (); Console.WriteLine ("3"); Auth1. Set (); Auth0. WaitOne (); Console.WriteLine ("5"); Auth1. Set (); } Static voidT1 () {auth1. WaitOne (); Console.WriteLine ("2"); Auth0. Set (); Auth1. WaitOne (); Console.WriteLine ("4"); Auth0. Set (); Auth1. WaitOne (); Console.WriteLine ("6"); }
Multiple threads correspond to multiple AutoResetEvent instances, initialization settings block False,waitone blocking, when set blocks become true, and AutoResetEvent automatically becomes fase after WaitOne.
After set, if multiple threads are waitone, a signal to continue execution is randomly sent to a thread.
Execution results
ManualResetEvent
Multiple threads will receive a release signal after 2.Set
StaticManualResetEvent MAuth0 =NewManualResetEvent (false);StaticManualResetEvent mAuth1 =NewManualResetEvent (false);Staticcirclequeue<BOOL> myqueue =Newcirclequeue<BOOL> (2);Static voidMain (string[] args) {Thread th=NewThread (t0); Th. IsBackground=true; Th. Start (); Thread Th1=NewThread (t1); Th1. IsBackground=true; Th1. Start (); Thread Th2=NewThread (T2); Th2. IsBackground=true; Th2. Start (); Console.ReadLine (); } Static voidT0 () {Console.WriteLine ("1-0"); Mauth1.set (); Mauth0.waitone (); Console.WriteLine ("2-0"); Mauth1.set (); } Static voidT1 () {BOOLR =Mauth1.waitone (); Myqueue.enqueue (R); Console.WriteLine ("2-1"); while(true) { BOOL[] ListA =Myqueue.getallqueue (); if(Lista.contains (false) ==false) { Break; } thread.sleep ( -); } mauth1.reset (); Mauth0.set (); Mauth1.waitone (); Console.WriteLine ("3-1"); } Static voidT2 () {BOOLR =Mauth1.waitone (); Myqueue.enqueue (R); Console.WriteLine ("2-2"); while(true) { BOOL[] ListA =Myqueue.getallqueue (); if(Lista.contains (false) ==false) { Break; } thread.sleep ( -); } mauth1.reset (); Mauth0.set (); Mauth1.waitone (); Console.WriteLine ("3-2"); }
Run results
The ring queue is used, and the next one is discussed.
AutoResetEvent and ManualResetEvent multithreaded applications