This question is from ExamsLab-5.0 final exam.
The doubt I have about this question is why wait method is not inside any synchronize block like this.
Actually both wait() and notify() method should be called from a synchronized block and by this Is owns a lock on same object, So I suspected IllegalMonitorException, but this questions. resulted in "Ready to Print, Now Printing, ". I ran it, It worked fine. I am still confused about it
the correct rule is wait and notify should be called while a thread is inside a monitor....
here when the thread executes synchronized method it is obviously inside the monitor of the implicit "this" object.....
so these methods(wait,notify,notifyAll) can be called
either from 1)synchronized block
or from 2)synchronized method
Balraj Momi wrote:Actually both wait() and notify() method should be called from a synchronized block and by this Is owns a lock on same object
I don't know what you mean by this but if you see, the call to wait in doMore is indeed in a synchronized context. The method doMore is synchronized. So it will have a lock on the this reference and the call to wait is just like calling this.wait(). you don't need to have a lock on the thread object. You are calling wait on the object on which the doMore method was called.
Sunny Narula wrote:Can anyone humor me and post the code it would take to actually print the last "Printed".
For that you need to notify on the object which is passed to the Thread constructor. Like this
But this code will only work if doMore is called before the main method enters the synchronized block. The sleeps will handle it nicely...
As ankit said for printed to print you have to see on what object its waiting. Here it is this.wait() means trd class. So we have to notify on the object only. The original code won't be useful as there is an anonymous instance created but ankit's scenario is good for the "printed"