0

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
  • Works, but it shows message immediately, not after 1000 mills Commented May 6, 2013 at 16:45

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Ok, so what would I change?
This is a duplicate of maybe 100 questions here.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.