多线程等待/通知机制
简介:一个线程修改了一个对象的值,而另外一个线程需要感知到这个值得变化才能dosomething。这时候就要用到等待/通知。
等待通知机制的经典范式:
等待方遵循包含如下
1.获取对象的锁
2.判断是否满足条件,不满足继续等待通知,被通知后检查条件
3.条件满足
通知方遵循如下
1.获取对象的锁
2.改变条件
3.通知等待的线程
代码如下:
class Program { static bool flag = true; public static object obj = new object(); static void Main(string[] args) { Thread threadWait = new Thread(new ThreadStart(() => { bool isLocked = false; Monitor.Enter(obj,ref isLocked); while (flag) //flag为true时 不满足时,继续wait,等待唤醒 { try { Console.WriteLine("线程id" + Thread.CurrentThread.ManagedThreadId + "条件不满足,线程处于等待状态:" + DateTime.Now.ToString("yyyy-MM-dd:mm:ss")); Monitor.Wait(obj); } catch (Exception ex) { Console.WriteLine(ex.Message); } finally { Monitor.Exit(obj); } } //条件满足时 Console.WriteLine("条件满足"); })); Thread threadNotify = new Thread(new ThreadStart(()=> { bool isLocked = false; Monitor.Enter(obj, ref isLocked); Console.WriteLine("线程获得锁" + Thread.CurrentThread.ManagedThreadId + ":" + DateTime.Now.ToString("yyyy-MM-dd:mm:ss")); Monitor.PulseAll(obj); flag = false; Thread.Sleep(3000); Monitor.Exit(obj); })); threadWait.Start(); Thread.Sleep(1000); threadNotify.Start(); Console.Read(); } }