C# AutoResetEvent简明教程

上例程

背景:张三李四互砍,你一刀,我一刀,公平互砍

using System;
using System.Threading;

namespace ConsoleApp1
{
    internal class Program
    {

        private static void Main(string[] args)
        {
            AutoResetEvent AManSuccess = new AutoResetEvent(true);
            AutoResetEvent BManSuccess = new AutoResetEvent(true);
            Man manOne = new Man("张三", AManSuccess, BManSuccess,1000);
            Man manTwo = new Man("李四", BManSuccess, AManSuccess,500);
            Thread thread1 = new Thread(new ThreadStart(manOne.Cut));
            Thread thread2 = new Thread(new ThreadStart(manTwo.Cut));
            thread1.Start();
            thread2.Start();
            //while (true)
            //{
            //    Console.ReadKey();
            //    BManSuccess.Set();
            //}
        }
    }

    public class Man
    {
        private string name = "";
        public Man(string name, AutoResetEvent safeManSuccess, AutoResetEvent friendsManSuccess,int delaytime)
        {
            this.name = name;
            this.safeManSuccess = safeManSuccess;
            this.friendsManSuccess = friendsManSuccess;
            this.delaytime = delaytime;
        }

        private AutoResetEvent safeManSuccess = null;
        private AutoResetEvent friendsManSuccess = null;
        private int delaytime = 0;

        public void Cut()
        {
            int index = 0;
            while (index++ < 30)
            {
                friendsManSuccess.WaitOne();
                Console.WriteLine(name + "砍第" + index + "刀");
                Thread.Sleep(delaytime);
                safeManSuccess.Set();
            }
        }

    }
}

运行结果

C# AutoResetEvent简明教程_第1张图片

用法

set():触发
waitOne():阻塞等待

你可能感兴趣的:(c#编程)