zoukankan      html  css  js  c++  java
  • ManualResetEvent同步与互斥

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading;
    
    namespace ConsoleApplication1
    {
        class Program
        {
            
            static void Main(string[] args)
            {
                EventWaitTest zhangsan = new EventWaitTest("张三");
                EventWaitTest lisi = new EventWaitTest("李四");
    
                Thread t1 = new Thread(new ThreadStart(zhangsan.Consume));
                Thread t2 = new Thread(new ThreadStart(lisi.Consume));
                Thread t3 = new Thread(new ThreadStart(EventWaitTest.Product));
    
                t1.Start();
                t2.Start();
                t3.Start();
    
                Console.Read();
    
            }
    
            
    
        }
    
        public class EventWaitTest
        {
            private string name; //顾客姓名  
            //private static AutoResetEvent eventWait = new AutoResetEvent(false);  
            private static ManualResetEvent eventWait = new ManualResetEvent(false);
            private static ManualResetEvent eventOver = new ManualResetEvent(false);
    
            public EventWaitTest(string name)
            {
                this.name = name;
            }
    
            public static void Product()
            {
                Console.WriteLine("服务员:厨师在做菜呢,两位稍等");
                Thread.Sleep(2000);
                Console.WriteLine("服务员:宫爆鸡丁好了");
                eventWait.Set();
                while (true)
                {
                    if (eventOver.WaitOne(1000, false))
                    {
                        Console.WriteLine("服务员:两位请买单");
                        eventOver.Reset();
                    }
                }
            }
    
            public void Consume()
            {
                while (true)
                {
                    if (eventWait.WaitOne(1000, false))
                    {
                        Console.WriteLine(this.name + ":开始吃宫爆鸡丁");
                        Thread.Sleep(2000);
                        Console.WriteLine(this.name + ":宫爆鸡丁吃光了");
                        eventWait.Reset();
                        eventOver.Set();
                        break;
                    }
                    else
                    {
                        Console.WriteLine(this.name + ":等着上菜无聊先玩会手机游戏");
                    }
                }
            }
        }
    }
    

     

  • 相关阅读:
    右建删除.svn
    Oracle 初始化 SEQUENCE附代码
    IE8支付宝密码控件
    JavaScript怎样读取Gridview控件的单元格的值
    IIS7 发布WCF
    C#创建后台服务注意事项
    Sqlserver中传递列参数需要注意的一个小细节
    JavaScript中针对中文参数的转编码
    VS2010里面调试后台服务
    href=#与href=javascriptvoid(0)的区别
  • 原文地址:https://www.cnblogs.com/wonderfuly/p/8584957.html
Copyright © 2011-2022 走看看