作為等同于Java的wait,notify,notifyAll的存在蒋搜,AutoResetEvent和ManualResetEvent分別實(shí)現(xiàn)了notify和notifyAll的功能幽钢,下面的代碼簡(jiǎn)單講解了一下實(shí)現(xiàn)原理赴肚,并展示了這一過程。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace ThreadTest
{
class Program
{
//新建一個(gè)默認(rèn)無信號(hào)的手動(dòng)重置線程事件
private void Test()
{
ManualResetEvent manualResetEvent = new ManualResetEvent(false);
AutoResetEvent autoResetEvent = new AutoResetEvent(false);
//線程傳參需要通過ParameterizedThreadStart委托奕巍,并在Start時(shí)附加參數(shù)。
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方法中锥涕,會(huì)讓信號(hào)狀態(tài)從無到有,從而讓所有wait狀態(tài)的線程喚醒请琳,實(shí)現(xiàn)NotifyAll
manualResetEvent.Set();
//autoResetEvent在Set方法中,會(huì)在第一個(gè)處于wait狀態(tài)的線程喚醒后將信號(hào)狀態(tài)Reset赠幕,變?yōu)闊o信號(hào)俄精,實(shí)現(xiàn)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;
}
}
}