Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Creating and Starting a Thread Properly

 
Sandra Bachan
Ranch Hand
Posts: 434
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
 
Paul Clapham
Sheriff
Pie
Posts: 20771
30
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 434
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic