my dog learned polymorphism*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Thread question doubt Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Thread question doubt" Watch "Thread question doubt" New topic
Author

Thread question doubt

Gaurang Rathod
Greenhorn

Joined: Oct 30, 2012
Posts: 22

Hello ranchers.
This is a question from Whizlabs diagnostic test:


Options:
a) prints "ABC"
b) prints "123"

Answer given is "ABC" and rightly so.
Why is answer not "123"?
How could main thread change myRunnable object's instance variable s[] ?

Thanks advance.
Ramesh Pramuditha Rathnayake
Ranch Hand

Joined: Oct 31, 2012
Posts: 169
    
    1

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.

s is changed after the t1 thread is terminated..!


Ramesh-X
Chintu Singh
Greenhorn

Joined: May 08, 2013
Posts: 20
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.


OCPJP
Chintu Singh
Greenhorn

Joined: May 08, 2013
Posts: 20
sleep method does not release the lock on myRunnable.
Chan Ag
Bartender

Joined: Sep 06, 2012
Posts: 1013
    
  15
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[] ?

Thanks advance.


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)?

Chan.
Chan Ag
Bartender

Joined: Sep 06, 2012
Posts: 1013
    
  15
Oops.. Sorry.. Didn't have Chintu Ji's responses when I started with my response.

Thread like things into play here too!
Gaurang Rathod
Greenhorn

Joined: Oct 30, 2012
Posts: 22

Yeah, got it now. Thanks for the replies.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Thread question doubt