This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Creating and Starting a Thread Properly Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Creating and Starting a Thread Properly" Watch "Creating and Starting a Thread Properly" New topic
Author

Creating and Starting a Thread Properly

Sandra Bachan
Ranch Hand

Joined: Feb 18, 2010
Posts: 434
Sierra/Bates, Chapter 9, Question 13

Given:


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



I thought the answer was B and C, but the answer is C and D.

How is it possible that exactly two of the code fragments might produce the output 4 4?

Fragment I doesn't start (or create) a thread
Fragment II doesn't compile
Fragment III creates a new thread, not start
Fragment IV invokes run directly, no new thread, so it is possible the output can be 4 4
Fragment V creates and starts a new thread, so it is possible the output can be 4 2

Hence, that is why my answer was B and C. Please explain why C and D is correct instead?

Marriage Made in Heaven
http://www.youtube.com/user/RohitWaliaWedsSonia
Paul Clapham
Bartender

Joined: Oct 14, 2005
Posts: 18541
    
    8

You haven't fully understood what Fragment I does. What you said about it was correct, but incomplete. What does it actually do?
Sandra Bachan
Ranch Hand

Joined: Feb 18, 2010
Posts: 434
Paul Clapham wrote:You haven't fully understood what Fragment I does. What you said about it was correct, but incomplete. What does it actually do?


Fragment one invokes run() as if it is a method in a regular class - OH MY :mrgreen:

Hence it may also output 4 4
 
Don't get me started about those stupid light bulbs.
 
subject: Creating and Starting a Thread Properly
 
Similar Threads
Regarding getId
Question 13 chapter 9 of k&B
Question of SCJP Guide by Kathy Sierra - Chapter Threads
Answering Strategy
Question on Threads