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?