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://blog.csdn.net/mx5721/article/details/36058391