lock Monitor 生产者消费者

  public class Cell
{
bool flags = false;
int result = 0;
public void Write(int n)
{
lock (this)
{
if (flags)
{
try
{
Monitor.Wait(this);
}
catch (ThreadStartException e)
{
Console.WriteLine(e);
}
}
result = n;
Console.WriteLine("写入:{0}", result);
flags = true;
Monitor.Pulse(this);
}
}
public int Read()
{
lock (this)
{
if (!flags)
{
try
{
Monitor.Wait(this);
}
catch (ThreadStartException e)
{
Console.WriteLine(e);
}
}
Console.WriteLine("读出:{0}", result);
flags = false;
Monitor.Pulse(this);
return result;
}

}
}
public class CellProd
{
Cell cell; // 被操作的Cell对象  
int quantity = 1; // 生产者生产次数,初始化为1   
public CellProd(Cell box, int request)
{
//构造函数
cell = box;
quantity = request;
}
public void ThreadRun()
{
for (int looper = 1; looper <= quantity; looper++)
cell.Write(looper); //生产者向操作对象写入信息  
}
}
public class CellCons
{
Cell cell;
int quantity = 1;
public CellCons(Cell box, int request)
{ //构造函数
cell = box;
quantity = request;
}
public void ThreadRun()
{
int valReturned; for (int looper = 1; looper <= quantity; looper++)
valReturned = cell.Read();//消费者从操作对象中读取信息  
}
}
class Program
{
public static void Add()
{
int result = 0;//一个标志位,如果是0表示程序没有出错,如果是1表明有错误发生
Cell cell = new Cell(); //下面使用cell初始化CellProd和CellCons两个类,生产和消费次数均为20次
CellProd Write = new CellProd(cell, 20);
CellCons Read = new CellCons(cell, 20);
Thread WriteTh = new Thread(new ThreadStart(Write.ThreadRun));
Thread ReadTh = new Thread(new ThreadStart(Read.ThreadRun)); //生产者线程和消费者线程都已经被创建,但是没有开始执行
try
{
ReadTh.Start();
WriteTh.Start();
ReadTh.Join();
WriteTh.Join();

Console.ReadLine();
}
catch (ThreadStateException e)
{
//当线程因为所处状态的原因而不能执行被请求的操作
Console.WriteLine(e); result = 1;
}
catch (ThreadInterruptedException e)
{
//当线程在等待状态的时候中止 
Console.WriteLine(e); result = 1;
} //尽管Main()函数没有返回值,但下面这条语句可以向父进程返回执行结果
Environment.ExitCode = result;
}

static void Main(string[] args)
{
Program.Add();
}

在上面的例程中,同步是通过等待Monitor.Pulse()来完成的。首先生产者生产了一个值,而同一时刻消费者处于等待状态,直到收到生产者的“脉冲(Pulse)”通知它生产已经完成,此后消费者进入消费状态,而生产者开始等待消费者完成操作后将调用Monitor.Pulese()发出的“脉冲”。

posted @ 2011-11-17 13:51  Rookier  阅读(377)  评论(0编辑  收藏  举报