AutoResetEvent:
构造方法:AutoResetEvent对象有两个状态,有信号和无信号,在初始化时可以分别用true和false指定
WaitOne:该对象在无信号时调用WaitOne方法,当前线程会阻塞,直到在其它线程中将其状态设置为有信号为止。有信号时调用并不会影响当前线程的执行
Set和Reset:Set()方法可以设置当前AutoResetEvent对象状态为有信号,Reset则设置为无信号
ManualResetEvent:
与AutoResetEvent基本相同,只不过Auto在调用Set方法后会自动调用Reset,从而保证只有一个线程能够继续执行,而Manual执行完set后则需要手动执行Reset,也就是可以保证多个线程继续执行
下面是一个用两个线程分别打印奇偶数的例子:
using System;
using System.Threading;
namespace ConsoleApp1
{
class Program
{
//若要将初始状态设置为终止,则为 true;若要将初始状态设置为非终止,则为 false
static AutoResetEvent oddResetEvent = new AutoResetEvent(false);
static AutoResetEvent evenResetEvent = new AutoResetEvent(false);
static int i = 0;
static void Main(string[] args)
{
//ThreadStart是个委托
Thread thread1 = new Thread(new ThreadStart(show));
thread1.Name = "偶数线程";
Thread thread2 = new Thread(new ThreadStart(show));
thread2.Name = "奇数线程";
thread1.Start();
Thread.Sleep(2); //保证偶数线程先运行。
thread2.Start();
Console.Read();
}
public static void show()
{
while (i <= 100)
{
int num = i % 2;
if (num == 0)
{
Console.WriteLine("{0}:{1} {2} ", Thread.CurrentThread.Name, i++, "evenResetEvent");
if (i != 1) evenResetEvent.Set();
oddResetEvent.WaitOne(); //当前线程阻塞
}
else
{
Console.WriteLine("{0}:{1} {2} ", Thread.CurrentThread.Name, i++, "oddResetEvent");
oddResetEvent.Set();
evenResetEvent.WaitOne();
}
}
}
}
}