等待获取java。lang.illegalMonitorStateException,如何修复它?
我有一个错误“java.lang.illegalMonitorStateException”,我不知道如何修复它。我知道notifyAll()似乎是原因,尽管我尝试了几种方法,例如放置同步块或其他东西,但我不太确定如何使用它。我习惯于在“public”之后加上“synchronized”,但这次我不能这么做。 基本上,每次msgQueue上出现新消息时,我都需要唤醒getNextMessage()函数,同时它被“阻止”
private LinkedList<NetClientSideMessage> msgQueue = new LinkedList<NetClientSideMessage>();
@Override
public ClientSideMessage getNextMessage() {
//wait for messages
if (hasNextMessage() == false)
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
// if connection is down, return null
if (isConnected() == false)
return null;
return msgQueue.getFirst();
}
@Override
public boolean hasNextMessage() {
// check if there are messages waiting in queue
if (msgQueue.size() > 0) {
notifyAll();
return true;
}
return false;
}
# 1 楼答案
您使用的
wait/notifyAll
没有锁!你不能这么做。向方法声明中添加synchronized应该可以修复它