线程等待例子
private static AutoResetEvent event_1 = new AutoResetEvent(true);
private static AutoResetEvent event_2 = new AutoResetEvent(false);
static void ThreadProc()
{
string name = Thread.CurrentThread.Name;
Console.WriteLine("{0} 等待自动复位事件# 1。 ", name);
event_1.WaitOne();
Console.WriteLine("{0} 从自动复位事件# 1发布。", name);
Console.WriteLine("{0} 等待自动复位事件# 2。", name);
event_2.WaitOne();
Console.WriteLine("{0} 从自动复位事件# 2发布。", name);
Console.WriteLine("{0} 结束.", name);
}
static void Main(string[] args)
{
起始:
Console.WriteLine("按回车键创建三个线程,然后开始 .\r\n" +
"线程等待自动复位事件# 1,创建了 \r\n" +
"在信号状态,所以第一个线程被释放 .\r\n" +
"这使得自动复位事件# 1成无信号状态。 ");
Console.ReadLine();
for (int i = 1; i < 4; i++)
{
Thread t = new Thread(ThreadProc);
t.Name = "Thread_" + i;
t.Start();
}
Thread.Sleep(250);
for (int i = 0; i < 2; i++)
{
Console.WriteLine("按回车键释放另一个线程。 ");
Console.ReadLine();
event_1.Set();
Thread.Sleep(250);
}
Console.WriteLine("\r\n所有的线程正在等待自动复位事件# 2。 ");
for (int i = 0; i < 3; i++)
{
Console.WriteLine("按回车键释放一个线程。 ");
Console.ReadLine();
event_2.Set();
Thread.Sleep(250);
}
}