Monitor同步的一个例子

网上看到一篇介绍Monitor同步的文章,写的挺好的。文中给了一个生产者消费者的例子,拿过来修改了一下,主要改动在于添加了边界条件和主应用程序的退出等待。
class MonitorWaitPulse
{
private int n = 1;
private int max = 5;

private object monitor = new object();

public void Produce()
{
lock (monitor)
{
for (; n <= max; n++)
{
Console.WriteLine("Mom:the " + n.ToString() + " cake is ready");
//tell the child that the cake is ready
Monitor.Pulse(monitor);
//if all cakes done,finish the job
if (n == max)
{
Console.WriteLine("Mom:job done");
break;
}
//wait the child to finishe the cake
Monitor.Wait(monitor);
}
}
}

public void Consume()
{
lock (monitor)
{
while (n <= max)
{
Console.WriteLine("Child:eat the " + n.ToString() + " cake");
//ask mom to make next cake
Monitor.Pulse(monitor);
if (n == max)
{
Console.WriteLine("Child: job done");
break;
}
//wait mom to make the cake
Monitor.Wait(monitor);
}
}
}

static void Main(string[] args)
{
MonitorWaitPulse obj = new MonitorWaitPulse();
Thread tProduce = new Thread(new ThreadStart(obj.Produce));
Thread tConsume = new Thread(new ThreadStart(obj.Consume));
//Start threads.
tProduce.Start();
tConsume.Start();

tProduce.Join();
tConsume.Join();
Console.ReadLine();
}
}

很简单的例子,就不做多的解释了,有兴趣的可以看原文,篇头有链接。

原文地址:https://www.cnblogs.com/rader/p/2210057.html