Pulse(lockObj)表示释放当前被lock的lockObj,容许其它线程调用。(相当于临时挂起当前线程)
Wait(lockObj)表示等待当前被其它线程占用的lockObj。
以下的代码将会交替运行两个线程:
class TickTock { object lockOn = new object(); public void Tick(bool running) { lock (lockOn) { if (!running) { Monitor.Pulse(lockOn); return; } Console.Write("Tick "); Monitor.Pulse(lockOn);//let tock() run Monitor.Wait(lockOn);//wait for tock() to complete } } public void Tock(bool running) { lock (lockOn) { if (!running) { Monitor.Pulse(lockOn); return; } Console.WriteLine("Tock"); Monitor.Pulse(lockOn); Monitor.Wait(lockOn); } } }
原文:http://www.cnblogs.com/hrhguanli/p/3915175.html