Java: IllegalMonitorStateException on notify()

天涯浪子 提交于 2019-12-12 03:03:20

问题


I am trying to call wait() function on the "slp" object, then after 1000 mills wake it up, but instead of message "Finished ..." I get an "IllegalMonitorStateException" error, after calling notify()

class Class1 extends Thread{

 boolean newTxt = false;
private Sleep slp = null;

synchronized public void put(Sleep slp)
{
  thus.slp = slp;
 try{ slp.wait();}catch(Exception x){} 

}
synchronized public void wakeup()
{
  slp.notify();
}
public void run()
{
  while(slp == null ); 
  try{ sleep(1000);}catch(Exception x){} 
  wakeup();

 }
}

class Sleep extends Thread {

Class1 t;
Sleep(Class1 t) {
this.t=t;
}
 public void run() {
 System.out.println("Started");
t.put(this);
System.out.println("Finished after 1000 mills");
 }

}

public class Koord {

  public static void main(String[] args) {
   Class1 t = new Class1();
 Sleep t1 = new Sleep(t);
 t1.start();
 t.start();
 }
}

回答1:


You need to be the "owner of the object's monitor" to be able to call notify on it.Your methods are all synchronized on this and you notify() on other objects. Just call wait() and notify().

IllegalMonitorStateException ,Thrown to indicate that a thread has attempted to wait on an object's monitor or to notify other threads waiting on an object's monitor without owning the specified monitor.



来源:https://stackoverflow.com/questions/16403189/java-illegalmonitorstateexception-on-notify

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!