using System;
using System.Threading;
namespace ConsoleHelper
{
internal class Program
{
static ManualResetEvent _mainEvent = new ManualResetEvent(false);
public static void TravelThroughGates(string threadName, int seconds)
{
Console.WriteLine($"{threadName} falls to sleep!");
Thread.Sleep(TimeSpan.FromSeconds(seconds));
Console.WriteLine($"{threadName} waits for the gates to open!"); // 3. thread 1 等待闸门打开
_mainEvent.WaitOne(); // 4. 阻止主线程
Console.WriteLine($"{threadName} enters the gates!"); // 6. thread1 进门
}
static void Main(string[] args)
{
var t1 = new Thread(() => TravelThroughGates("thread 1", 5)); // 1. 启动三个线程 分别执行5,6,12秒
var t2 = new Thread(() => TravelThroughGates("thread 2", 6));
var t3 = new Thread(() => TravelThroughGates("thread 3", 12));
t1.Start();
t2.Start();
t3.Start();
Thread.Sleep(TimeSpan.FromSeconds(6)); // 2. 主线程工作6秒
Console.WriteLine("The gates are now open!");
_mainEvent.Set(); // 5. 主线程打开闸门 2s
Thread.Sleep(TimeSpan.FromSeconds(2));
_mainEvent.Reset(); // 7. 主线程关闭闸门
Console.WriteLine("The gates have been closed!");
Thread.Sleep(TimeSpan.FromSeconds(10));
Console.WriteLine("The gates are now open for the second time!");
_mainEvent.Set(); // 8. 主线程打开闸门2s
Thread.Sleep(TimeSpan.FromSeconds(2));
Console.WriteLine("The gates have been closed!");
_mainEvent.Reset(); // 9. 主线程关闭闸门
Console.ReadLine();
}
}
}
ManualResetEvent: 类似打开闸门,在此期间,线程可以自由运行,一但闸门关闭,相关线程应运行到wait位置。
执行步骤
1. 启动三个线程 分别执行5,6,12秒
2. 主线程工作6秒
3. thread 1 等待闸门打开
4. 阻止主线程
5. 主线程打开闸门 2s
6. thread1 进门
7. 主线程关闭闸门
8. 主线程打开闸门2s
9. 主线程关闭闸门
thread 3 falls to sleep!
thread 1 falls to sleep!
thread 2 falls to sleep!
thread 1 waits for the gates to open!
The gates are now open!
thread 1 enters the gates!
thread 2 waits for the gates to open!
thread 2 enters the gates!
The gates have been closed!
thread 3 waits for the gates to open!
The gates are now open for the second time!
thread 3 enters the gates!
The gates have been closed!