Wrapping a Thread around a Thread (as a Runnable): what does this program print? class MyThread extends Thread { public static void main(String[] args) { MyThread t = new MyThread(); Thread x = new Thread(t); x.start(); } public void run() { for (int i = 0; i < 3; ++i) { System.out.print(i + ".."); } } }
-
ACompilation fails
-
B1..2..3..
-
C0..1..2..3..
-
D0..1..2..
-
ENo output
Answer
Correct Answer: 0..1..2..
Explanation
Introduction / Context: A Thread can take any Runnable, and Thread itself implements Runnable. If you pass a Thread (that overrides run()) as the target to another Thread, the outer Thread will invoke the target’s run() just like any Runnable. This is legal though unusual.
Given Data / Assumptions:
- Class MyThread extends Thread and overrides run() to print i from 0 to 2.
- main constructs MyThread t, then constructs a new Thread x with t as its Runnable target, and starts x.
Concept / Approach: Starting x results in x’s internal run() delegating to the target Runnable’s run(), which is t.run(). Therefore, the overridden run() in MyThread executes on thread x and prints 0..1..2..
Step-by-Step Solution:
Create t (a Thread subclass) — not started directly.Create x = new Thread(t).Call x.start() → new thread calls t.run().Loop prints 0.. 1.. 2..Verification / Alternative check: If main had called t.start() instead, you would still see 0..1..2.. (on a different thread) and possibly two sets if both were started.
Why Other Options Are Wrong:
- Bounds do not produce 3..; loop ends at i < 3.
- No compilation problems are present.
Common Pitfalls: Assuming a Thread cannot be used as a Runnable target; expecting an exception or double printing.
Final Answer: 0..1..2..