zoukankan      html  css  js  c++  java
  • 多线程信号源_红绿灯

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;

    using System.Threading;

    namespace ConsoleApplication1
    {
        class Program
        {
            static AutoResetEvent greenLight = new AutoResetEvent(false);
            static AutoResetEvent redLight = new AutoResetEvent(false);
            static void Main(string[] args)
            {
                Thread t1 = new Thread(new ThreadStart(M1));
                Thread t2 = new Thread(new ThreadStart(M2));

                t1.Start();
                t2.Start();

                //这个是主线程语句,相当于说现在是有3个线程。
                greenLight.Set();
            }

            static void M1()
            {
                while (true)
                {
                    if (greenLight.WaitOne())
                    {
                        Console.WriteLine("绿灯了。行人过马路!");
                        Thread.Sleep(3000);
                        redLight.Set();//红灯了
                    }
                }
            }
            static void M2()
            {
                while (true)
                {
                    if (redLight.WaitOne())
                    {
                        Console.WriteLine("红灯了。行人等待!");
                        Thread.Sleep(3000);
                        greenLight.Set();
                    }
                }
            }
        }
    }
  • 相关阅读:
    步步为营 SharePoint 开发学习笔记系列总结
    Type 关键字解读
    C# 利用反射方便取得DbDataReader里的值
    WCF 开发学习笔记
    用状态模式实现状态机工作流
    步步为营UML建模系列总结
    策略模式实现支持多种类数据库的DBHelp
    步步为营 .NET 设计模式学习笔记系列总结
    BPEL 语言介绍和应用
    步步为营 .NET 代码重构学习笔记系列总结
  • 原文地址:https://www.cnblogs.com/pnljs/p/3551785.html
Copyright © 2011-2022 走看看