大家好,又见面了,我是你们的朋友全栈君。
原文来自:http://www.cnblogs.com/tianzhiliang/archive/2011/03/04/1970726.html
1. 源码下载:
下载地址:http://files.cnblogs.com/tianzhiliang/ManualResetEventDemo.rar
Demo:

2. ManualResetEvent详解
ManualResetEvent 允许线程通过发信号互相通信。通常,此通信涉及一个线程在其他线程进行之前必须完成的任务。当一个线程开始一个活动(此活动必须完成后,其他线程才能开始)时,它调用 Reset 以将 ManualResetEvent 置于非终止状态,此线程可被视为控制 ManualResetEvent。调用 ManualResetEvent 上的 WaitOne 的线程将阻止,并等待信号。当控制线程完成活动时,它调用 Set 以发出等待线程可以继续进行的信号。并释放所有等待线程。一旦它被终止,ManualResetEvent 将保持终止状态(即对 WaitOne 的调用的线程将立即返回,并不阻塞),直到它被手动重置。可以通过将布尔值传递给构造函数来控制 ManualResetEvent 的初始状态,如果初始状态处于终止状态,为 true;否则为 false。
usingSystem;
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.Text;
usingSystem.Threading;
namespaceManualResetEventDemo
{
classMREDemo
{
privateManualResetEvent _mre;
publicMREDemo()
{
this._mre = newManualResetEvent(true);
}
publicvoidCreateThreads()
{
Thread t1 = newThread(newThreadStart(Run));
t1.Start();
Thread t2 = newThread(newThreadStart(Run));
t2.Start();
}
publicvoidSet()
{
this._mre.Set();
}
publicvoidReset()
{
this._mre.Reset();
}
privatevoidRun()
{
stringstrThreadID = string.Empty;
try
{
while(true)
{
// 阻塞当前线程
this._mre.WaitOne();
strThreadID = Thread.CurrentThread.ManagedThreadId.ToString();
Console.WriteLine("Thread("+ strThreadID + ") is running...");
Thread.Sleep(5000);
}
}
catch(Exception ex)
{
Console.WriteLine("线程("+ strThreadID + ")发生异常!错误描述:"+ ex.Message.ToString());
}
}
}
}
|
usingSystem;
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.Text;
namespaceManualResetEventDemo
{
classProgram
{
staticvoidMain(string[] args)
{
Console.WriteLine("****************************");
Console.WriteLine("输入\"stop\"停止线程运行...");
Console.WriteLine("输入\"run\"开启线程运行...");
Console.WriteLine("****************************\r\n");
MREDemo objMRE = newMREDemo();
objMRE.CreateThreads();
while(true)
{
stringinput = Console.ReadLine();
if(input.Trim().ToLower() == "stop")
{
Console.WriteLine("线程已停止运行...");
objMRE.Reset();
}
elseif(input.Trim().ToLower() == "run")
{
Console.WriteLine("线程开启运行...");
objMRE.Set();
}
}
}
}
}
|
转载于:https://www.cnblogs.com/nele/p/5552451.html
发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/161167.html原文链接:https://javaforall.net
