This week's book giveaway is in the OCPJP forum. We're giving away four copies of OCA/OCP Java SE 7 Programmer I & II Study Guide and have Kathy Sierra & Bert Bates on-line! See this thread for details.
wait(), notify(), and notifyAll() must be called from within a synchronized context! A thread can't invoke a wait or notify method on an object unless it owns that object's lock.
In the first code sample, main thread has acquired lock on the object which is created in 2 line and its invoking the notifyAll() method on a new objet which is created inside the synchorized block. As the main thread doesnt own the lock on the object on which notifyAll() is invoked, it will throw runtime exception "IllegalMonitorStateException".
In the second example, the thread is trying to invoke the notifyAll() method on object r and it owns the lock on r. Thats the reason code compiles and runs properly!
Thanks,<br />Srilatha M
Joined: Jul 07, 2008
thanks Rekha Srinath & M SRILATHA for your response