zoukankan      html  css  js  c++  java
  • 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();
    }
    }

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

  • 相关阅读:
    abstract关键字
    final关键字
    Vue使用枚举类型实现HTML下拉框
    第八节 pandas读取和保存文件
    第七节 pandas新建数据框的两种方式
    第六节 numpy的常用属性和方法
    第五节 numpy的简单使用
    第三节 matplotlib绘制直方图
    第三节 matplotlib绘制条形图
    第二节 matplotlib绘制散点图
  • 原文地址:https://www.cnblogs.com/rader/p/2210057.html
Copyright © 2011-2022 走看看