Interview question
What is Thread Lifecycle in Java? Explain all thread states. Java में Thread Lifecycle क्या है? सभी states explain करें।
Answer
Thread lifecycle consists of five states: New, Runnable, Running, Blocked/Waiting, and Terminated. Understanding state transitions is crucial for multithreading.
| State | Description | Transition |
|---|---|---|
| New | Thread created but not started | start() called |
| Runnable | Ready to run, waiting for CPU | Scheduler selects |
| Running | Currently executing | Context switch |
| Blocked/Waiting | Waiting for resource/event | Resource available |
| Terminated | Finished execution | End of run() |
public class ThreadLifecycleDemo {
public static void main(String[] args) {
Thread t = new Thread(() -> {
System.out.println('Thread is running');
try {
Thread.sleep(2000); // Waiting state
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println('Thread finished');
});
System.out.println('State: ' + t.getState()); // NEW
t.start();
System.out.println('State: ' + t.getState()); // RUNNABLE
try {
t.join(); // Wait for thread to finish
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println('State: ' + t.getState()); // TERMINATED
}
}
// Thread state transitions:
// New -> Runnable: start() called
// Runnable -> Running: Scheduler selects
// Running -> Runnable: Context switch
// Running -> Waiting: sleep(), wait(), join()
// Waiting -> Runnable: notify(), time expires
// Running -> Terminated: run() ends
// Thread.State enum values:
// NEW, RUNNABLE, BLOCKED, WAITING, TIMED_WAITING, TERMINATEDThread States:
1. NEW: Thread create हुआ, start() नहीं हुआ
2. RUNNABLE: CPU के लिए ready
3. RUNNING: Actively executing
4. BLOCKED/WAITING: Resource के लिए wait
5. TERMINATED: Complete हो गया
State Transitions:
NEW -> start() -> RUNNABLE
RUNNABLE -> Scheduler -> RUNNING
RUNNING -> sleep()/wait() -> WAITING
WAITING -> notify()/time -> RUNNABLE
RUNNING -> end() -> TERMINATEDWas this answer clear?