The array s is initialized by 1,2 and 3 when creating the instance MyRunnable class.
In line 18, you have started t1 (with MyRunnable). And in the next line current thread(Main thread) has been gone to the sleep mode for 4 seconds. It is more that enough to finish the t1 thread. Therefore 1,2,3 is printed.
When jvm runs the code in the main method's synchronized block, even after starting the thread t1 which has myRunnable as target cannot run the thread as it needs lock on myRunnable to run the thread. And the lock is not available as it is alraedy taken by main method.
So main method's synchronized block will complete and set the entries in array as A, B and C.
And after the releaseing the lock from main method's synchronized block, it will print ABC as per run method of MyRunnable.
I hope this solves your doubt.
Joined: May 08, 2013
sleep method does not release the lock on myRunnable.
Gaurang Rathod wrote:Hello ranchers.
Answer given is "ABC" and rightly so.
Why is answer not "123"?
How could main thread change myRunnable object's instance variable s ?
Why would you think it should be 123. What happens after you have invoked sleep in your main() method? Would the two threads interleave? What happens if you increase or decrease the sleep interval? Does that affect your output in anyway ( besides the time taken to execute the program)?
Joined: Sep 06, 2012
Oops.. Sorry.. Didn't have Chintu Ji's responses when I started with my response.