代码1:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</exclusion>
</exclusions>
</dependency>
代码2:
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();
}
}
代码3:
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();
}
}
}
代码4:
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();
}
}
}
注意:有来自其他地方的通知
在代码1中没有等待的条件,因此存在无限等待,但为什么在其他3个代码(2,3,4)中发生无限等待 请仔细检查代码中的注释以便更好地理解请帮助我,我是java中的新手等待并通知
答案 0 :(得分:1)
我的示例我没有看到任何lock.notify()
或lock.notifyAll()
次调用。
简短而简单的回答:您将wait()
取消联系notify()
同一个对象lock
。
如需其他信息,请考虑查看下一个链接: