【发布时间】:2016-12-13 11:37:42
【问题描述】:
代码 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)
请检查代码中的 cmets更好的理解请帮助我我是java新手等待并通知
【问题讨论】:
-
这就是相关代码的全部吗?值 someCondition 永远不会设置为 true
标签: java synchronization wait