Wrapping a Thread around a Thread (as a Runnable): what does this program print?\n\nclass MyThread extends Thread {\n public static void main(String[] args) {\n MyThread t = new MyThread();\n Thread x = new Thread(t);\n x.start();\n }\n public void run() {\n for (int i = 0; i < 3; ++i) {\n System.out.print(i + "..");\n }\n }\n}

Difficulty: Easy

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..

More Questions from Threads

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion