vs2015-》新建控制台项目-》代码如下
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
namespace AutoResetEvent_test
{
class Program
{
static void Main(string[] args)
{
Thread payMoneyThread = new Thread(new ThreadStart(PayMoneyProc));
payMoneyThread.Name = "付钱线程";
Thread getBookThread = new Thread(new ThreadStart(GetBookProc));
getBookThread.Name = "取书线程";
payMoneyThread.Start();
getBookThread.Start();
for (int i = 1; i <= numIterations; i++)
{
Console.WriteLine("客户{0}选好了书", i);
number = i;
//Signal that a value has been written.
myResetEvent.Set();
Thread.Sleep(0);
ChangeEvent.Set();
Thread.Sleep(5);
}
payMoneyThread.Abort();
getBookThread.Abort();
Console.ReadKey();
}
const int numIterations = 50;
static AutoResetEvent myResetEvent = new AutoResetEvent(false);
static AutoResetEvent ChangeEvent = new AutoResetEvent(false);
//static ManualResetEvent myResetEvent = new ManualResetEvent(false);
//static ManualResetEvent ChangeEvent = new ManualResetEvent(false);
static int number; //这是关键资源
static void PayMoneyProc()
{
while (true)
{
myResetEvent.WaitOne();
//myResetEvent.Reset();
Console.WriteLine("{0}:客户{1}付钱", Thread.CurrentThread.Name, number);
}
}
static void GetBookProc()
{
while (true)
{
ChangeEvent.WaitOne();
// ChangeEvent.Reset();
Console.WriteLine("{0}:客户{1}取书", Thread.CurrentThread.Name, number);
Console.WriteLine("------------------------------------------");
Thread.Sleep(0);
}
}
}
}
通过控制AutoResetEvent set的先后顺序,管理线程运行的顺序,和时间。
AutoResetEvent与ManualResetEvent的区别
他们的用法\声明都很类似:
Set方法将信号置为发送状态
Reset方法将信号置为不发送状态
WaitOne等待信号的发送。其实,从名字就可以看出一个手动,
一个自动,这个手动和自动实际指的是在Reset方法的处理上,如下面例子:
public AutoResetEvent autoevent=new AutoResetEvent(true);
public ManualResetEvent manualevent=new ManualResetEvent(true);
默认信号都处于发送状态,
autoevent.WaitOne();
manualevent.WaitOne();
ManualResetEvent在WaitOne();进入之后需要增加Reset方法,才能执行下一次set方法,否者set方法无效。而AutoResetEvent会自动Reset方法