【问题标题】:Getting the java.lang.illegalMonitorStateException, how to fix it? [duplicate]获取 java.lang.illegalMonitorStateException,如何解决? [复制]
【发布时间】: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


【解决方案1】:

你使用wait/notifyAll 没有锁!你根本做不到。在方法声明中添加同步应该可以解决它。

public synchronized ClientSideMessage getNextMessage() {
}

public synchronized boolean hasNextMessage() {
  ..
}

【讨论】:

  • 是的,这就是它,我觉得自己很愚蠢。不知道我可以添加同步的..谢谢!
  • @JRed:API 和关于这个主题的所有其他类似问题都会告诉你同样的事情。
猜你喜欢
  • 2018-12-24
  • 2017-04-03
  • 2020-02-07
  • 2021-08-21
  • 2021-12-28
  • 1970-01-01
  • 1970-01-01
  • 2021-09-24
  • 2012-05-14
相关资源
最近更新 更多