Java notify是否立即调用等待的线程?
我正在编写一个Java代码,其中在满足特定条件后,在等待线程上调用notify,但等待线程不会立即开始运行。原因可能是什么?Java notify是否立即调用等待的线程?,java,Java,我正在编写一个Java代码,其中在满足特定条件后,在等待线程上调用notify,但等待线程不会立即开始运行。原因可能是什么?等待(以及通知)需要采取同步监视器。如果调用notify的代码没有释放它,则wait将继续“等待”,直到释放监视器 // wait thread synchronized (syncObject) { syncObject.wait(); // to proceed to next line, // this thread
等待
(以及通知
)需要采取同步监视器。如果调用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
}
很难回答你的问题,因为它没有包含一个。显示代码比描述代码要好得多。请将您的问题包括您的代码、示例输入和输出以及预期与实际行为。这将帮助我们更好地回答您的问题。我将用示例更新这个问题。“但等待线程不会立即开始运行”,因为JVM决定何时启动它,而不是您的调用。对它调用
notify
,只会告诉JVM这个线程应该重新启动。