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

Java Programming Threads Difficulty: Easy
Choose an option
  • A
    Prints "Inside Thread Inside Thread"
  • B
    Prints "Inside Thread Inside Runnable"
  • C
    Compilation error
  • D
    Runtime exception thrown
  • E
    No output due to deadlock

Answer

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"

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