notifyAll()抛出IllegalMonitorStateException

New*_*wyo 5 java concurrency multithreading

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

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

}
Run Code Online (Sandbox Code Playgroud)

我做错了什么?

Jon*_*eet 15

你正在打电话waitnotify没有同步你正在等待或通知的事情.作为记录在Object.notifyAll:

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

所以这:

synchronized(nameSetLock){
  notifyAll();
}
Run Code Online (Sandbox Code Playgroud)

应该:

synchronized(nameSetLock){
  nameSetLock.notifyAll();
}
Run Code Online (Sandbox Code Playgroud)

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