This week's book giveaway is in the OO, Patterns, UML and Refactoring forum.
We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line!
See this thread for details.
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: 43980
    
  33
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’ve looked at a lot of different solutions, and in my humble opinion Aspose is the way to go. Here’s the link: http://aspose.com
 
subject: Threading code snippet confusion
 
It's not a secret anymore!