110,538
社区成员
发帖
与我相关
我的任务
分享
using System;
using System.Threading;
namespace AutoResetEvent_Examples
{
class MyMainClass
{
//初始的时候是没有信号的,这里的意思是指参数false
const int numIterations = 10; //重复次数设置多少都无所谓,为让大家看清楚设置了100
static AutoResetEvent myResetEvent = new AutoResetEvent(false);
static int number;
static void Main()
{
//创建并开始一个线程。
Thread myReaderThread = new Thread(new ThreadStart(MyReadThreadProc));
myReaderThread.Name = "副线程";
myReaderThread.Start();
for (int i = 1; i <= numIterations; i++)
{
Console.WriteLine("-----主线程的Number数值: {0}", i);
number = i;
//发信号,说明值已经被写进去了。这里的意思是说Set是一个发信号的方法。
myResetEvent.Set();
//*************设置当前线程睡眠时间*****************
//第一次测试时间间隔为20,保证每次myResetEvent.Set()释放当前资源时副线程都有足够的时间捕获并且运行
//第二次测试时间间隔为0;主线程释放资源,但立刻对资源进行申请
Thread.Sleep(20);
}
//终止阅读线程。
myReaderThread.Abort();
Console.ReadLine();
}
static void MyReadThreadProc()
{
while (true)
{
//在数据被作者写入之前不会被读者读取
//在上次读取之前至少有一次。
myResetEvent.WaitOne();
Console.WriteLine("{0} 的Number数值: {1}", Thread.CurrentThread.Name, number);
}
}
}
}