java线程是否可能在wait()循环中饿死?
假设我有这个方法
/*1*/ public synchronized void method1() throws InterruptedException {
while (condition)
/*2*/ wait();
/*3*/ notify();
}
假设在第二行等待条件中有一个Thread 1
,那么线程1将处于状态WAITING
现在Thread 2
进入,它不满足条件,因此它绕过while循环,然后Thread 2
在第3行调用notify
,然后Thread 1
应该将其状态从WAITING
更改为BLOCKED
,直到Thread 2
完全退出
现在假设,在线程2完全退出之前,Thread 3
在同步块之外BLOCKED
以获取监视器
是否可能Thread 3
在Thread 1
之前获取锁?对于Thread 4
和Thread 5
等等,情况是否相同?在这种情况下,Thread-1
将处于饥饿状态
这在概念上是可能的吗
编辑:如果是这样,我如何防止饥饿
# 1 楼答案
不能使用
synchronized
关键字阻止它。但是,您可以使用ReentrantLock
,因为它允许“公平”锁定请记住,公平锁定是有代价的,你应该有真正的理由使用它
来自JavaDochttps://docs.oracle.com/javase/7/docs/api/java/util/concurrent/locks/ReentrantLock.html