Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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) {}
       }
     }

}

What have I done wrong?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
217 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

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

So this:

synchronized(nameSetLock){
  notifyAll();
}

should be:

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

... 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...