假设线程 T1 正在等待进入同步块(synchronized block),线程 T2 在同步块(synchronized block)内 wait()
,并且线程 T3 在同步块(synchronized block)上调用 notify()
block 的监视器。
T1有可能在T2继续之前进入区 block 吗?还是T2优先?
最佳答案
Is it possible for T1 to enter the block before T2 proceeds?
是的,这是可能的。 Object.wait(int)
的 javadoc没有指定已通知的线程优先。事实上,它指定应用正常调度规则。
<小时/>"The thread T is then removed from the wait set for this object and re-enabled for thread scheduling. It then competes in the usual manner with other threads for the right to synchronize on the object ..."
这是您需要编写这样的条件变量代码的原因之一
private boolean condition = ...
private Object lock = new Object(); // mutex for 'condition'
...
synchronize (lock) {
while (!condition) {
wait(lock);
// It is UNSAFE to assume that 'condition' is true now.
}
}
关于java - notify()之后的锁获取顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32446393/