多线程之ManualResetEvent关键字

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!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值