Java threads: calling run() directly vs starting a new thread. class MyThread extends Thread { public static void main(String[] args) { MyThread t = new MyThread(); t.run(); } public void run() { for (int i = 1; i < 3; ++i) { System.out.print(i + ".."); } } }
-
ACompilation error on construction
-
BCompilation error on run() call
-
C1..2..
-
D1..2..3..
-
ENo output is produced
Answer
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..