线程同步——Monitor

作者:追风剑情 发布于:2017-9-22 17:01 分类:C#

示例
using System;
using System.Threading;

namespace MonitorTest
{
    class Program
    {
        private static object lock_obj = new object();
        static void Main(string[] args)
        {
            Thread myThread;
            for (int i = 0; i < 5; i++)
            {
                myThread = new Thread(new ThreadStart(MyThreadProc));
                myThread.Name = String.Format("Thread{0}", i + 1);
                myThread.Start();
            }

            //等待一会确保最后创建的一条线程已经启动并执行到Wait
            Thread.Sleep(200);
            
            Monitor.Enter(lock_obj);
            Thread.Sleep(2000);
            Console.WriteLine("2秒后唤醒处于Wait中的所有线程");
            Monitor.PulseAll(lock_obj);//唤醒处于Wait中的所有线程
            //Monitor.Pulse(lock_obj);//唤醒处于Wait中的某条线程
            Monitor.Exit(lock_obj);
            
            Console.ReadKey();
        }

        private static void MyThreadProc()
        {
            string name = Thread.CurrentThread.Name;
            //Monitor.Enter与Monitor.Exit之间的代码相当于lock(){}

            Monitor.Enter(lock_obj);//开始线程同步,相当于lock(){}
            Console.WriteLine("{0} Thread Enter", name);

            Console.WriteLine("{0} Wait...", name);
            Monitor.Wait(lock_obj);//阻塞当前线程

            Console.WriteLine("{0} Thread Exit", name);
            Monitor.Exit(lock_obj);//结束线程同步
        }
    }
}


运行测试

11111.png

官方文档 https://msdn.microsoft.com/zh-cn/library/system.threading.monitor(v=vs.110).aspx

标签: C#

Powered by emlog  蜀ICP备18021003号-1   sitemap

川公网安备 51019002001593号