任何人都可以通过简单的例子来解释我处理Monitor.PulseAll().我已经从这个stackoverflow中得到了一些例子.因为我是初学者,我觉得这些都在我头顶.
怎么样(显示交互):
static void Main()
{
object obj = new object();
Console.WriteLine("Main thread wants the lock");
lock (obj)
{
Console.WriteLine("Main thread has the lock...");
ThreadPool.QueueUserWorkItem(ThreadMethod, obj);
Thread.Sleep(1000);
Console.WriteLine("Main thread about to wait...");
Monitor.Wait(obj); // this releases and re-acquires the lock
Console.WriteLine("Main thread woke up");
}
Console.WriteLine("Main thread has released the lock");
}
static void ThreadMethod(object obj)
{
Console.WriteLine("Pool thread wants the lock");
lock (obj)
{
Console.WriteLine("Pool thread has the lock");
Console.WriteLine("(press return)");
Console.ReadLine();
Monitor.PulseAll(obj); // this signals, but doesn't release the lock
Console.WriteLine("Pool thread has pulsed");
}
Console.WriteLine("Pool thread has released the lock");
}
Run Code Online (Sandbox Code Playgroud)
重新发信号; 在处理Monitor(又名lock)时,有两种类型的阻塞; 有"就绪队列",其中线程排队等待执行.Console.WriteLine("Pool thread wants the lock");池队列进入就绪队列后的行.释放锁定后,就绪队列中的线程可以获取锁定.
第二个队列用于需要唤醒的线程; 调用Wait将线程放在第二个队列中(并临时释放锁).调用PulseAll将所有线程从第二个队列Pulse移动到就绪队列(仅移动一个线程),这样当池线程释放锁时,主线程可以再次获取锁.
这听起来很复杂(也许是这样) - 但它听起来并不像听起来那么糟糕......老实说.但是,线程代码总是很棘手,需要谨慎和明确地处理.