I was going through the Thread Self Test Question #12 in Page 767 given in the "Kathy Sierra & Bert Bates" SCJP 6 Study Guide and I quite understood it. Then I modified the question as is given below. I made the laurel.wait() to synchronize on laurel. Then what I see is, hardy waits and continues, once the laurel came out from the sleep after one second.
Does it mean that laurel obtains a lock on itself and notifies hardy once it releases the lock, though there was no synchronized keyword used within the laurel run method? My understanding was that, a 'wait' can continue only upon a 'notification' which must be through an explicit 'notify' invocation and sleep would never notify.
The reason why I ask is, if I comment-out the sleep code within laurel(including its exception handling), then the synchronized wait in hardy waits forever.
A reply is much appreciated.
The modified code snippet is given below in the bold font.
The output obtained was:-
A <- from laurel
D <- from hardy, then hardy waits
C <- from laurel after 1000 milli seconds
F <- from hardy, out from the waiting
If 'sleep' from laurel is removed including the try-catch, output is
A <- from laurel
C <- from laurel
D <- from hardy, then hardy waits indefinitely.
program waits indefinitely.
Rajanand P K, Oracle Certified Professional, Java SE 6 Programmer.
Rajanand Pandaraparambil Kuttappan
Joined: Oct 26, 2011
Anyone to extend help on this ?
If its because of a too lengthy content in the original mail, let me sum-up my queries down here.
1) Thread.sleep within an InterruptedException try-catch block - does it obtain a lock on the thread object, though there is no explicit synchronized block specified around it ?
2) Once the thread is out from the sleep and completes the run method, does it notify the other threads waiting on the this thread object ?
If answers are NO, then I am not able reason out the behavior I observed in the code snippet I posted with the original content. Though, as far as I read and understood, sleep does not obtain any lock implicitly.