Reputation: 1012
I have the following Java code:
public class Lean extends Thread
{
public static void main(String args[]) throws InterruptedException
{
Lean lean = new Lean();
System.out.println("starting");
lean.start();
lean.join();
System.out.println("end");
}
public void run()
{
try
{
System.out.println("waiting");
wait(20000);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
finally
{
System.out.println("waiting finished");
}
}
}
Output is (keeps on changing -- sometimes I do not even see "end" printed )
starting
waiting
waiting finished
end
Exception in thread "Thread-1" java.lang.IllegalMonitorStateException
at java.lang.Object.wait(Native Method)
at Lean.run(Lean.java:18)
Questions:
Why do I get IllegalMonitorStateException
exception?
Why does thread.join not work the way it is expected to be? (I do not see see "end" printed sometimes)
Upvotes: 0
Views: 382
Reputation: 37835
IllegalMonitorStateException
is thrown when operations that require synchronization are called without holding the monitor lock. wait
needs to be called in a synchronized block.
The documentation for wait
covers this.
Basically you need to do:
synchronized(this) {
wait();
}
This has nothing to do with the interruption mechanism.
Upvotes: 7