![](/img/trans.png)
[英]java.lang.IllegalMonitorStateException: Current thread is not owner of the lock
[英]Java 8 Reentrant Lock and Condition results in IllegalMonitorStateException: current thread is not owner
我已经在这里搜索了这个错误,但我认为我的一段代码看起来是正确的:
这是代码的摘录,如果我试图运行代码,我会得到一个 java.lang.IllegalMonitorStateException: current thread is not owner。 错误在 cond.wait() 方法中。
public void takeARest() {
lock.lock();
try {
while (disembark < totalPassengers) {
System.err.printf("Held by %s%n",lock.isHeldByCurrentThread());
cond.wait();
}
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
有任何想法吗?
为此,您需要Condition.await()
。
Object.wait()
是一种不同的方法,它需要保持对象的监视器(在调用周围的synchornized(cond){}
)
所以:
public void takeARest() {
lock.lock();
try {
while (disembark < totalPassengers) {
System.err.printf("Held by %s%n",lock.isHeldByCurrentThread());
cond.await();
}
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.