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.
When I run the above code I get no output. If I change Line 1 to synchronize on "this":
or change Line 2 to:
I get the desired output - "Running".
What is happening in the original code and why does the print statement not execute? Is this due to the lock on the object being synchronized which has to be called such as s.wait(5); instead of just wait(5); ?
Second question is, why can't we call wait(), notify(), notifyAll() in a static method? is this because there is no "this" in a static method?
In the original code when you call wait, it is a call to wait on the this reference. Since the call to wait is not in synchronized context of this, so a IllegalMonitorStateException is thrown. Since the associated catch block does nothing when an exception is raised, so you see no output.
You are right that calling s.wait(5); will solve the problem as the code is synchronized on s. But that is not a perfect solution. The call to wait will return only because of timeout i.e. the 5 milliseconds will expire. The call will not return if you write s.wait() as no one notifies it.
So the correct code would be something like this
you cannot call wait, notify and notifyAll in static methods because they are non-static methods in Object class and you need the this reference (which is like an object not a method) to access them...
[Edit: Removed the logical error that Santiago and Srilatha are referring below in this thread] [ December 03, 2008: Message edited by: Ankit Garg ]