Here the run() method is synchronizing the code on this. So, does it mean, it is synchronizing on t1 object? Also, then it calls wait(); and since there is no notify(), it will keep on waiting indefinitely. What changes do we need to make in the program to make it print "Notified" also? I am finding thread questions quite difficult to handle. I would be greatful, if somebody cam explain me this program step by step.
EDIT by mw: Added Code Tags. (See how much better that looks? ) [ March 28, 2007: Message edited by: marc weber ]
You may ask why some changes I made to your code. First in the run method, you made synchronized(this). Here this means current executing thread (thread because your class extends Thread). So therefore t1 will be refering to "this" there.
And in the startme() method you make synchronized to whole class, that is different thing, that notification wont reach to the threads that are waiting for this, so there will be indefinite wait in the run method. So for the sake of that, I made both of the methods synchronize on the same monitor "this".
You may ask why sleep() in the restart() method, that is because your notification statement block may get executed prior to the run method wait; that is because of underlining scheduling criteria. You can't rely on that. So for that to give the time the run method could get executed getting the "this" monitor first, I made the sleep() method to be called before startme() could be called by the restart() method.
First there should be wait and wait after any criteria matches, here we used boolean to make sure whether to wait or not, before notification boolean variable is made true by the startme() method.
That is the whole funda, Any doubt?
Thanks and Regards, cmbhatt [ March 28, 2007: Message edited by: Chandra Bhatt ]
Originally posted by Lovleen Gupta: ...Here the run() method is synchronizing the code on this. So, does it mean, it is synchronizing on t1 object? ...
Yes, "this" refers to the current instance, and t1 references the only instance created.
Originally posted by Lovleen Gupta: ...Also, then it calls wait(); and since there is no notify(), it will keep on waiting indefinitely. What changes do we need to make in the program to make it print "Notified" also? ...
Remember, each instance has an object lock, but there is also a separate class lock. Your waiting thread is waiting to re-acquire the object lock. So instead of synchronizing the code in startme on the class (using the class lock), you could synchronize on the object (this). Then the thread waiting for the object lock will be notified.
Another way to get "Notified" to print would be to simply add a "time-out" parameter to the wait call. For example, if you call wait(5000), then the thread will stop waiting after 5 seconds.
"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer sscce.org