Hi, I would like to know why is that the follo prog. prints only some of the nos thru 0-9 and not all of them.
Joined: Jul 07, 2003
Sanjana, Here is a neat answer for u....Infact, thank you for a good question!!! Okay, I just ran the code with couple of println statements here & there and got myself a convincing answer:: the code creates 10 objects and also starts 10 unique threads in a for loop. Remember, these are threads and have their own piece of memory for execution. Hence, while the FOR loop keeps on creating objects & subsequently threads, the THREADS which are already created earlier would start waiting on a common object and subsequently, releases their LOCKS on the common object (remember wait()!!! releases LOCKS & goes to waiting state). Soon after the control comes out of the for loop, it acquires the lock of the COMMON object (same object which is required by the waiting threads to resume their execution) and issues a NOTIFYALL() which is a single call for all threads..... Sometimes (infact mostly), the threads created at the last step of the for loop (probably, counter no. 8/9) would be scheduled to enter the run() a little late by the THREAD SCHEDULER. If this latency or elapsed time is beyond the duration of notifyAll() call, your threads will keep on waiting assuming, someone will notify me !!!..... but the corresponding NOTIFYALL is already been issued and hence, only certain nos. will be printed on account of this and would subsequently the prog. won't stop running and will keep on waiting!!!... HOPE U UNDERSTAND THIS LONG EXPLANATION...just want you to visualise the process going on in depth....just insert print statements in each method block of wait, notify & for loop....u'll understand urself!!... ~ Shalini
Joined: Oct 02, 2003
Hi, Sanjana Just try to put these lines right before the sychronized block inside method m1():
These lines give time to all the children threads to be able to call wait(). [ January 22, 2004: Message edited by: Yosi Hendarsjah ]