代码1:
class BCWCExamples {
public Object lock;
boolean someCondition;
public void NoChecking() throws InterruptedException {
synchronized(lock) {
//Defect due to not checking a wait condition at all
lock.wait();
}
}
代码2:
public void IfCheck() throws InterruptedException {
synchronized(lock) {
// Defect due to not checking the wait condition with a loop.
// If the wait is woken up by a spurious wakeup, we may continue
// without someCondition becoming true.
if(!someCondition) {
lock.wait();
}
}
}
代码3:
public void OutsideLockLoop() throws InterruptedException {
// Defect. It is possible for someCondition to become true after
// the check but before acquiring the lock. This would cause this thread
// to wait unnecessarily, potentially for quite a long time.
while(!someCondition) {
synchronized(lock) {
lock.wait();
}
}
}
代码4:
public void Correct() throws InterruptedException {
// Correct checking of the wait condition. The condition is checked
// before waiting inside the locked region, and is rechecked after wait
// returns.
synchronized(lock) {
while(!someCondition) {
lock.wait();
}
}
}
}
注意:有其他地方的通知
代码1中没有等待条件,因此存在无限等待,但为什么其他3个代码(2,3,4)中发生无限等待
请检查代码中的注释以便更好地理解请帮助我,我是java等待和通知的新手
最佳答案
在您的示例中,我没有看到任何 lock.notify()
或 lock.notifyAll()
调用。
简短的回答:您将wait()
除非您在同一个对象lock
上调用notify()
。
有关更多信息,请考虑查看下一个链接:
关于java无限等待问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41120182/