问题
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