AutoResetEvent
1.用于在多线程,对线程进行阻塞放行
static AutoResetEvent auth0 = new AutoResetEvent(false); static AutoResetEvent auth1 = new AutoResetEvent(false); static void Main(string[] args) { Thread th = new Thread(t0); th.IsBackground = true; th.Start(); Thread th1 = new Thread(t1); th1.IsBackground = true; th1.Start(); Console.ReadLine(); } static void t0() { Console.WriteLine("1"); auth1.Set(); auth0.WaitOne(); Console.WriteLine("3"); auth1.Set(); auth0.WaitOne(); Console.WriteLine("5"); auth1.Set(); } static void t1() { auth1.WaitOne(); Console.WriteLine("2"); auth0.Set(); auth1.WaitOne(); Console.WriteLine("4"); auth0.Set(); auth1.WaitOne(); Console.WriteLine("6"); }
多个线程对应多个 AutoResetEvent 实例,初始化设置阻塞false,WaitOne进行阻塞,当Set之后阻塞变成true程序进行,另外WaitOne之后AutoResetEvent会自动变成fase。
Set之后,若多个线程都WaitOne,会随机向某个线程发送继续执行的信号。
执行结果如图
ManualResetEvent
2.Set之后多个线程会收到放行信号
static ManualResetEvent mAuth0 = new ManualResetEvent(false); static ManualResetEvent mAuth1 = new ManualResetEvent(false); static CircleQueue<bool> MyQueue = new CircleQueue<bool>(2); static void Main(string[] args) { Thread th = new Thread(t0); th.IsBackground = true; th.Start(); Thread th1 = new Thread(t1); th1.IsBackground = true; th1.Start(); Thread th2 = new Thread(t2); th2.IsBackground = true; th2.Start(); Console.ReadLine(); } static void t0() { Console.WriteLine("1-0"); mAuth1.Set(); mAuth0.WaitOne(); Console.WriteLine("2-0"); mAuth1.Set(); } static void t1() { bool r = mAuth1.WaitOne(); MyQueue.EnQueue(r); Console.WriteLine("2-1"); while (true) { bool[] ListA = MyQueue.GetAllQueue(); if (ListA.Contains(false) == false) { break; } Thread.Sleep(50); } mAuth1.Reset(); mAuth0.Set(); mAuth1.WaitOne(); Console.WriteLine("3-1"); } static void t2() { bool r = mAuth1.WaitOne(); MyQueue.EnQueue(r); Console.WriteLine("2-2"); while (true) { bool[] ListA = MyQueue.GetAllQueue(); if (ListA.Contains(false) == false) { break; } Thread.Sleep(50); } mAuth1.Reset(); mAuth0.Set(); mAuth1.WaitOne(); Console.WriteLine("3-2"); }
运行结果
其中用到了环形队列,下次再讨论。