📖 Thread Life Cycle:
A thread goes through various states from creation to termination.
5 States: New, Runnable, Running, Blocked/Waiting, Terminated
💡 Analogy: Like attending an exam — New (registered), Runnable (waiting outside), Running (writing exam), Blocked (waiting for pen), Terminated (submitted).
Thread States in Detail:
1. New (Born) State:
Thread created but not yet started.
How: Thread t = new Thread();
2. Runnable State:
Thread ready to run, waiting for CPU time.
How: t.start();
3. Running State:
Thread executing its run() method - CPU allocated.
How: Thread scheduler selects from runnable pool.
4. Blocked/Waiting State:
Thread temporarily inactive, waiting for resource or I/O.
How: sleep(), wait(), I/O operations, waiting for lock
5. Terminated (Dead) State:
Thread finished execution or stopped. Cannot be restarted.
How: run() method completes, or stop() called
Thread Life Cycle Diagram:
NEW
|
| start()
↓
RUNNABLE ←──────────────┐
| |
| Scheduler picks | I/O complete, notify()
↓ | sleep() time up
RUNNING |
| |
| sleep(), wait() |
| I/O request |
↓ |
BLOCKED/WAITING ─────────┘
RUNNING
|
| run() completes
↓
TERMINATED
Thread State Methods:
// Check thread state
Thread t = new Thread();
System.out.println(t.getState()); // NEW
t.start();
System.out.println(t.getState()); // RUNNABLE
// Thread state constants:
Thread.State.NEW
Thread.State.RUNNABLE
Thread.State.BLOCKED
Thread.State.WAITING
Thread.State.TIMED_WAITING
Thread.State.TERMINATED
Complete Life Cycle Example:
class LifeCycleThread extends Thread {
public void run() {
System.out.println("State: RUNNING");
try {
Thread.sleep(2000); // Goes to TIMED_WAITING
System.out.println("Woke up from sleep");
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("About to terminate");
}
}
public class ThreadLifeCycle {
public static void main(String[] args) throws InterruptedException {
LifeCycleThread t = new LifeCycleThread();
System.out.println("After creation: " + t.getState()); // NEW
t.start();
System.out.println("After start(): " + t.getState()); // RUNNABLE
Thread.sleep(100);
System.out.println("While sleeping: " + t.getState()); // TIMED_WAITING
t.join(); // Wait for thread to complete
System.out.println("After completion: " + t.getState()); // TERMINATED
}
}
Output:
After creation: NEW
After start(): RUNNABLE
State: RUNNING
While sleeping: TIMED_WAITING
Woke up from sleep
About to terminate
After completion: TERMINATED