Java threads: calling run() directly vs starting a new thread.\n\nclass MyThread extends Thread {\n public static void main(String[] args) {\n MyThread t = new MyThread();\n t.run();\n }\n public void run() {\n for (int i = 1; i < 3; ++i) {\n System.out.print(i + "..");\n }\n }\n}

Difficulty: Easy

Correct Answer: 1..2..

Explanation:


Introduction / Context:
The distinction between Thread.start() and Thread.run() is fundamental in Java concurrency. start() creates a new thread of execution and then invokes run() on that new thread. Calling run() directly executes the method on the current thread (here, main), with no concurrency.



Given Data / Assumptions:

  • A class extends Thread and overrides run().
  • main creates MyThread and calls t.run() directly.
  • The loop prints i from 1 to 2 inclusive.


Concept / Approach:
The loop bounds are i = 1; i < 3; ++i → values 1 and 2. Because run() is called like a normal method, it executes on the main thread and simply prints text; there is no second thread involved, but the output tokens are unaffected.



Step-by-Step Solution:

Instantiate MyThread.Invoke run() directly in main.Loop prints 1.. then 2..Program ends normally.


Verification / Alternative check:
If t.start() were used, the same text would print, but on another thread and with potential interleavings with other concurrent output.



Why Other Options Are Wrong:

  • Compilation errors do not exist in this snippet.
  • 1..2..3.. would require i <= 3 or a different bound.
  • “No output” contradicts the loop execution.


Common Pitfalls:
Confusing run() for start(); expecting new-thread behavior without calling start().



Final Answer:
1..2..

More Questions from Threads

Discussion & Comments

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