首页 > 解决方案 > notify 会立即调用等待线程吗?

问题描述

我正在编写一个 Java 代码,其中在满足特定条件后在等待线程上调用 notify,但等待线程不会立即开始运行。可能是什么原因?

标签: java

解决方案


wait(以及notify)需要进行同步监视器。如果调用的代码notify没有释放它,那么wait将继续“等待”直到监视器被释放

// wait thread
synchronized (syncObject) {
   syncObject.wait(); // to proceed to next line, 
                      // this thread must wait until notify is called 
                      // and then take ownership over syncObject
   // next line
}

...

// notify thread
synchronized (syncObject) {
   syncObject.wait();
   while (true) {}; // infinite loop, syncObject is never released, 
                    // wait thread will never gain ownership over syncObject 
                    // and will never wake up 
}

推荐阅读