AutoResetEvent 类用于线程通信
class Program
{
static AutoResetEvent auto0 = new AutoResetEvent(false);
//这里传入的布尔值是是否设置初始状态为终止的布尔参数
static AutoResetEvent auto1 = new AutoResetEvent(false);
static AutoResetEvent auto2 = new AutoResetEvent(false);
static AutoResetEvent auto3 = new AutoResetEvent(false);
static void Main(string[] args)
{
Thread t1 = new Thread(pay);
t1.Name = "1";
Thread t2 = new Thread(eat);
t2.Name = "2";
//将两个线程开始,但是由于存在waitone,线程会被终止
t1.Start();
t2.Start();
for (int i = 0; i < 20; i++)
{
Console.WriteLine(i);
auto0.Set();//线程开始运行
auto3.WaitOne();//线程等待一次
auto1.Set();
auto2.WaitOne();
//Console.WriteLine("---------------");
//Thread.Sleep(0);
}
Thread.Sleep(10);
t1.Abort();
t2.Abort();
Console.Read();
}
public static void pay() {
while (true)
{
auto0.WaitOne();
Console.WriteLine("付钱线程开始");
auto3.Set();
}
}
public static void eat() {
while (true)
{
auto1.WaitOne();
Console.WriteLine("付完钱可以吃了");
auto2.Set();
}
}
}
运行结果如下