Skip to content
C

Thread Lifecycle

The thread lifecycle describes the different stages a thread passes through during its existence: New, Runnable, Running, Blocked/Waiting, and Terminated.


1. What is the Thread Lifecycle?

The thread lifecycle describes the different stages a thread passes through during its existence: New, Runnable, Running, Blocked/Waiting, and Terminated.

2. Why is it used?

Understanding these stages helps you know exactly what state a thread is in at any given moment, which is important for debugging multithreaded programs and understanding why a thread might be paused or waiting.

3. Real-Life Example

Think of a student's day: waking up (New), waiting in line for the bus (Runnable), actually attending class (Running), waiting during a break for the next class (Waiting), and finally going home at the end of the day (Terminated).

4. Syntax

java
// Lifecycle stages are managed internally by the JVM // but can be observed using thread state methods Thread.State state = thread.getState();

5. Example Program

java
public class ThreadLifecycleDemo { public static void main(String[] args) throws InterruptedException { Thread t = new Thread(() -> System.out.println("Running")); System.out.println("State before start: " + t.getState()); t.start(); t.join(); System.out.println("State after completion: " + t.getState()); } }

Output:

State before start: NEW
Running
State after completion: TERMINATED

6. Key Points to Remember

  • A thread cannot go back to an earlier stage once it moves forward — for example, a terminated thread cannot be restarted.
  • The "Runnable" state means a thread is ready to run but may not currently be executing (the CPU decides scheduling).
  • getState() is useful for understanding a thread's current lifecycle stage during debugging.