gpt4 book ai didi

java - java中的IllegalMonitorStateException

转载 作者:行者123 更新时间:2023-12-02 00:11:28 24 4
gpt4 key购买 nike

嗨,我正在尝试使用 Java 套接字编程制作多人游戏。我的服务器正在使用多线程环境。问题是,我希望当两个玩家都连接到服务器时,他们就可以继续前进,否则不...这个原因我使用循环运行两次并接受来自两个客户端的连接。在循环中我使用线程对象并调用其等待方法。当循环完成时我调用 obj.notifyALl 方法,以便当前线程和前一个三人应该醒来,他们将开始工作但我遇到了这个异常......欢迎任何想法或建议......

最佳答案

简而言之:您正在等待或通知尚未同步的对象。

来自Object.wait()

The current thread must own this object's monitor. The thread releases ownership of this monitor and waits until another thread notifies threads waiting on this object's monitor to wake up either through a call to the notify method or the notifyAll method. The thread then waits until it can re-obtain ownership of the monitor and resumes execution.

As in the one argument version, interrupts and spurious wakeups are possible, and this method should always be used in a loop:

 synchronized (obj) {
while (<condition does not hold>)
obj.wait();
... // Perform action appropriate to condition
}

IllegalMonitorStateException - if the current thread is not the owner of the object's monitor.

恕我直言,您可能应该使用 concurrency library而不是等待/通知。

关于java - java中的IllegalMonitorStateException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12742156/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com