After this if i also remove the lines with ob2 i don't get any exception. How come removing ob2 affects ob1 and prevents the program from throwing exception ?
I tried this (removing ob2) and I still got the same exceptions in the console:
Exception in thread "One" java.lang.IllegalMonitorStateException: current thread
not owner
at java.lang.Object.wait(Native Method)
at java.lang.Object.wait(Unknown Source)
at NewThread.run(suspendresume.java:59)
at java.lang.Thread.run(Unknown Source)
The key seems to be "current thread not owner".
In the Method Summary section of the Thread class api, scroll down to the section "Methods inherited from class java.lang.Object" and find the
notify and
wait methods.
Look these up in the Object class api and read the information in the Method Detail for each. It specifies the conditions required for a thread to obtain a lock on, and thus be the owner of, an objects monitor.
You can test this in the NewThread class with the addition of a print statement in the
run method:
synchronized (this) {
Thread thread = Thread.currentThread();
System.out.printf("name = %s holdsLock = %b%n",
thread.getName(),
Thread.holdsLock(this));
while (suspendFlag) {
wait();
}
}
and see what happens in the console when you run the app with and without commenting out the two lines for the "synchronized(this)" block.