File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes Threading code snippet confusion Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Threading code snippet confusion" Watch "Threading code snippet confusion" New topic
Author

Threading code snippet confusion

Mansukhdeep Thind
Ranch Hand

Joined: Jul 27, 2010
Posts: 1157

Hi

Have a look at the following piece of code:



And given the following five fragments:

I. new Starter().run();
II. new Starter().start();
III. new Thread(new Starter());
IV. new Thread(new Starter()).run();
V. new Thread(new Starter()).start();

When the five fragments are inserted, one at a time at line 9, which are true? (Choose all that apply.)

A. All five will compile
B. Only one might produce the output 4 4
C. Only one might produce the output 4 2
D. Exactly two might produce the output 4 4
E. Exactly two might produce the output 4 2
F. Exactly three might produce the output 4 4
G. Exactly three might produce the output 4 2

The answer is C and D options are correct. How are we getting to this conclusion? What does Thread.currentThread().getId() return? Why only 4 2 and 4 4? I am not able to follow the flow in this snippet. Can someone please provide a clue as to how to go about such questions?


~ Mansukh
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38765
    
  23
Please always tell us where you found such questions.
Mansukhdeep Thind
Ranch Hand

Joined: Jul 27, 2010
Posts: 1157

It is a part of the self test exercise in the Threads chapter of Kathy's book SCJP for java 6.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Threading code snippet confusion