线程同步——AutoResetEvent

作者:追风剑情 发布于:2017-9-21 11:00 分类:C#

控制线程同步

示例

using System;
using System.Threading;

namespace AutoResetEventTest
{
    class Program
    {
        private static AutoResetEvent event_1 = new AutoResetEvent(true);
        private static AutoResetEvent event_2 = new AutoResetEvent(true);

        static void Main(string[] args)
        {
            Thread myThread;
            for (int i = 0; i < 10; i++)
            {
                myThread = new Thread(new ThreadStart(MyThreadProc));
                myThread.Name = String.Format("Thread{0}", i + 1);
                myThread.Start();
                Thread.Sleep(1);
            }

            Console.ReadKey();
        }

        private static void MyThreadProc()
        {
            //线程按先后顺序依次执行something1和something2
            string name = Thread.CurrentThread.Name;
            //同时只允许1条线程执行something 1
            event_1.WaitOne();
            Console.WriteLine("{0} Thread do something 1...", name);
            Thread.Sleep(100);
            event_1.Set();

            //同时只允许1条线程执行something 2
            event_2.WaitOne();
            Console.WriteLine("{0} Thread do something 2...", name);
            Thread.Sleep(100);
            event_2.Set();
        }
    }
}

运行测试

1111.png

标签: C#

Powered by emlog  蜀ICP备18021003号-1   sitemap

川公网安备 51019002001593号