notifyAll() 抛出 IllegalMonitorStateException [英] notifyAll() throws IllegalMonitorStateException

查看:38
本文介绍了notifyAll() 抛出 IllegalMonitorStateException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在设计两个线程:一个必须获取玩家的名字,第二个线程必须等待名称设置才能继续,但是第一个线程中的 notify() 都抛出了 IllegalMonitorStateException 错误.

I am designing two threads: one has to get the name of players, and the second thread has to wait for the name being set in order to continue, but notify() all in the first thread is throwing the IllegalMonitorStateException error.

private NameFecth nameFetch;
private UseName useName;
private Object nameSetLock; 
public static void method{
   nameSetLock = new Object()
   nameFetch = new NameFetch(nameSetLock);
   useName = new UseName(nameSetLock);
   Thread nameFetchThread = new Thread(nameFetch);
   nameFetchThread.start();
   Thread useNameThread = new Thread(useName);
   useNameThread.start();
}

public class NameFetch implements Runnable{
    /*variables and constructers*/

    public void run(){
       /*get name and set the variable somehow*/
       synchronized(nameSetLock){
         notifyAll();
       }
    }
}

public class UseName implements Runnable{
    /*variables and constructers*/

   public void run(){
     while(!nameBeenSet){
       synchronized(nameSetLock){
         try{
           wait();
         }catch(InterruptedException e) {}
       }
     }

}

我做错了什么?

推荐答案

您正在调用 waitnotify 而没有同步您正在等待或通知的事情.如 Object.notifyAll 中所述:

You're calling wait and notify without synchronizing on the thing you're waiting on or notifying. As documented in Object.notifyAll:

投掷:
IllegalMonitorStateException - 如果当前线程不是此对象监视器的所有者.

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

所以:

synchronized(nameSetLock){
  notifyAll();
}

应该是:

synchronized(nameSetLock){
  nameSetLock.notifyAll();
}

... 和 wait 同上.请注意,当您使用 syncronized 而不是 synchronized 时,您当前的代码甚至无法编译,这表明您没有发布实际 代码.有可能在输入代码时您实际上改变了问题 - 在这种情况下,您应该编辑您的问题以使其更具代表性.

... and ditto for wait. Note that your current code wouldn't even compile as you're using syncronized rather than synchronized, which suggests that you didn't post your actual code. It's possible that in typing out the code you've actually changed the problem - in which case you should edit your question to be more representative.

这篇关于notifyAll() 抛出 IllegalMonitorStateException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆