Thread vs Runnable target when subclass overrides run(): what prints?\n\nclass MyThread extends Thread {\n MyThread() {}\n MyThread(Runnable r) { super(r); }\n public void run() { System.out.print("Inside Thread "); }\n}\nclass MyRunnable implements Runnable {\n public void run() { System.out.print(" Inside Runnable"); }\n}\nclass Test {\n public static void main(String[] args) {\n new MyThread().start();\n new MyThread(new MyRunnable()).start();\n }\n}

Difficulty: Easy

Correct Answer: Prints "Inside Thread Inside Thread"

Explanation:


Introduction / Context:
A Thread can be constructed with a Runnable target. By default, Thread.run() delegates to the target’s run() if present. However, if you subclass Thread and override run(), your override takes precedence and does not automatically call the target’s run().



Given Data / Assumptions:

  • MyThread extends Thread and overrides run() to print “Inside Thread ”.
  • One MyThread is created with no target; another is created with a MyRunnable target that prints “ Inside Runnable”.
  • Neither override calls super.run().


Concept / Approach:
Because MyThread.run() overrides the inherited behavior, the Runnable target’s run() is never invoked in either case (unless explicitly called). Therefore, both started threads execute MyThread.run(), printing the same message twice.



Step-by-Step Solution:

First start: executes MyThread.run() → prints “Inside Thread ”.Second start with Runnable target: still executes MyThread.run() → prints “Inside Thread ” again.Combined output contains two “Inside Thread ” tokens (order may vary due to scheduling).


Verification / Alternative check:
To invoke the target’s run(), remove the override or call super.run() inside MyThread.run(); the second thread would then print the Runnable’s text.



Why Other Options Are Wrong:

  • “Inside Thread Inside Runnable” would require Thread.run() to be used (or super.run() called).
  • No syntax or runtime errors exist.


Common Pitfalls:
Assuming Thread always delegates to its target; forgetting that subclass overrides replace the delegation unless they call super.run().



Final Answer:
Prints "Inside Thread Inside Thread"

More Questions from Threads

Discussion & Comments

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