首页 > 代码库 > lock模拟CountDownEvent

lock模拟CountDownEvent

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
namespace ConsoleApplication44
{
    class Class2
    {
        public readonly static object _locker = new object();
        public static bool _singal;
        public static int _count;
        public static void Main()
        {
            _count = 3;
            for (int i = 1; i <= 3; i++)
            {

                new Thread(DoWork).Start(i);
            }
            Wait();
            Console.WriteLine("Compelete!");
            Console.ReadKey();

        }
        public static void DoWork(object i)
        {

            Set();
            Console.WriteLine(i);


        }

        public static void Set()
        {
            lock (_locker)
            {
                _count--;
                Monitor.PulseAll(_locker);
            }

        }
        public static void Wait()
        {
            lock (_locker)
            {
                while (_count > 0) { Monitor.Wait(_locker); }
            }
        }

    }
}

 

lock模拟CountDownEvent