【发布时间】:2015-11-29 22:52:51
【问题描述】:
我有这个错误“java.lang.illegalMonitorStateException”,我不知道如何修复它。我知道 notifyAll() 似乎是原因,虽然我尝试了几件事,比如放置同步块或其他东西,但我不太确定如何使用它。我习惯把“同步”这个词放在“公众”之后,但这次我不能这样做。 基本上,每当 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;
}
【问题讨论】:
-
阅读 wait() 和 notifyAll() 的 javadoc。那里都有解释。
标签: java wait synchronized notify