c# 多线程编程中AutoResetEvent和ManualResetEvent

作为等同于Java的wait,notify,notifyAll的存在,AutoResetEvent和ManualResetEvent分别实现了notify和notifyAll的功能,下面的代码简单讲解了一下实现原理,并展示了这一过程。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace ThreadTest
{
    class Program
    {
        //新建一个默认无信号的手动重置线程事件
        private void Test()
        {
            ManualResetEvent manualResetEvent = new ManualResetEvent(false);
            AutoResetEvent autoResetEvent = new AutoResetEvent(false);
            //线程传参需要通过ParameterizedThreadStart委托,并在Start时附加参数。
            new Thread(new ParameterizedThreadStart(MyThreadHandler)).Start(new ParamStruct("Thread1", manualResetEvent));
            new Thread(new ParameterizedThreadStart(MyThreadHandler)).Start(new ParamStruct("Thread2", manualResetEvent));
            new Thread(new ParameterizedThreadStart(MyThreadHandler)).Start(new ParamStruct("Thread3", autoResetEvent));
            new Thread(new ParameterizedThreadStart(MyThreadHandler)).Start(new ParamStruct("Thread4", autoResetEvent));
            Thread.Sleep(1000);
            //manualResetEvent在Set方法中,会让信号状态从无到有,从而让所有wait状态的线程唤醒,实现NotifyAll
            manualResetEvent.Set();
            //autoResetEvent在Set方法中,会在第一个处于wait状态的线程唤醒后将信号状态Reset,变为无信号,实现NotifyOne
            autoResetEvent.Set();
            Thread.Sleep(1000);
            autoResetEvent.Set();
            Console.ReadKey();
        }
        static void Main(string[] args)
        {
            new Program().Test();
        }
        private void MyThreadHandler(object obj)
        {
            if (obj is ParamStruct paramStruct)
            {
                Console.WriteLine(paramStruct.threadName);
                paramStruct.resetEvent.WaitOne();
                Console.WriteLine(paramStruct.threadName + " finished on " + DateTime.Now);
            }
        }
    }
    class ParamStruct
    {
        public string threadName;
        public EventWaitHandle resetEvent;
        public ParamStruct(string threadName, EventWaitHandle resetEvent)
        {
            this.threadName = threadName;
            this.resetEvent = resetEvent;
        }
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 1. Java基础部分 基础部分的顺序:基本语法,类相关的语法,内部类的语法,继承相关的语法,异常的语法,线程的语...
    子非鱼_t_阅读 31,785评论 18 399
  • 从三月份找实习到现在,面了一些公司,挂了不少,但最终还是拿到小米、百度、阿里、京东、新浪、CVTE、乐视家的研发岗...
    时芥蓝阅读 42,382评论 11 349
  • 本文出自 Eddy Wiki ,转载请注明出处:http://eddy.wiki/interview-java.h...
    eddy_wiki阅读 2,250评论 0 14
  • 我昨天突然悟出一个道理,之所以我的闺蜜们都是精品,那是因为闺蜜的妈妈们都是人精。 昨天一事业风生水起,家庭和美甜蜜...
    墙角玫开阅读 592评论 0 1
  • 作者:云烟 一片片落叶连成片 连成数不清的秋意缠绵 一只只飞雁串成行 串成一行行如箭的归心 是家乡的秋红寄来红豆相...
    当代诗人云烟阅读 352评论 0 0