Java threads — starting a thread that implements Runnable. Given: class X implements Runnable { public static void main(String args[]) { // Which line starts a new thread correctly? } public void run() {} }
-
AThread t = new Thread(X);
-
BThread t = new Thread(X); t.start();
-
CX run = new X(); Thread t = new Thread(run); t.start();
-
DThread t = new Thread(); x.run();
-
ENone of the above
Answer
Correct Answer: X run = new X(); Thread t = new Thread(run); t.start();
Explanation
Introduction / Context:There are two standard ways to create threads in Java: extend Thread, or implement Runnable and pass an instance to a Thread constructor. This question focuses on the Runnable approach and proper instantiation.
Given Data / Assumptions:
- Class
XimplementsRunnableand correctly definesrun(). - We need the exact code to start a new thread of execution.
Concept / Approach:To start a thread using Runnable, you must: (1) create a Runnable object; (2) wrap it in a Thread by calling the appropriate constructor; (3) invoke start() on the Thread, not run(). Calling run() directly runs code on the current thread rather than creating a new one.
Step-by-Step Solution:
Create a Runnable:X run = new X();Create a Thread: Thread t = new Thread(run);Start the thread: t.start();Verification / Alternative check:At runtime, t.start() transitions the new thread into the runnable state and schedules a call to run() on that thread. Directly calling run() would not create a separate thread.
Why Other Options Are Wrong:new Thread(X) passes a Class literal, not a Runnable instance; t.start() is missing in some options; calling x.run() executes on the current thread and does not start a new one.
Common Pitfalls:Forgetting to call start(); passing the class name rather than an instance; confusing run() with start().
Final Answer:X run = new X(); Thread t = new Thread(run); t.start();