Thread Lifecycle
TL;DR
A Java thread goes through various states in its lifecycle, managed by the JVM and OS. The 6 states are:
- NEW: Created, but
start()not called. - RUNNABLE: Ready to run (or currently running).
- BLOCKED: Waiting to acquire a lock.
- WAITING: Waiting indefinitely for another thread to signal it.
- TIMED_WAITING: Waiting for a specified amount of time (e.g.,
sleep(1000)). - TERMINATED: Finished execution.
Concept
Understanding the lifecycle is crucial for debugging deadlocks and performance issues.
- When you type
new Thread(), it is NEW. - When you type
thread.start(), it moves to RUNNABLE. (Note: It might not be executing on the CPU instantly, it is waiting in the thread scheduler’s queue, but Java considers both “ready” and “running” as the same RUNNABLE state). - If the thread needs to enter a
synchronizedblock, but another thread is already in there, it goes to BLOCKED. - If the thread calls
Thread.sleep(5000), it goes to TIMED_WAITING for 5 seconds. - Once the
run()method finishes naturally, the thread enters TERMINATED and is destroyed.
Examples
public class ThreadLifecycle {
public static void main(String[] args) throws InterruptedException {
Thread t1 = new Thread(() -> {
try {
// Moving into TIMED_WAITING state
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
});
// State: NEW
System.out.println("Before start: " + t1.getState());
t1.start();
// State: RUNNABLE
System.out.println("After start: " + t1.getState());
// Sleep main thread slightly to ensure t1 hits the Thread.sleep line
Thread.sleep(500);
// State: TIMED_WAITING
System.out.println("While sleeping: " + t1.getState());
// Wait for t1 to completely finish
t1.join();
// State: TERMINATED
System.out.println("After finish: " + t1.getState());
}
}
Interview Questions
Q: Can you restart a TERMINATED thread?
A: No. Once a thread completes its execution and enters the TERMINATED state, it is permanently dead. If you attempt to call t1.start() on a dead thread, Java will throw an IllegalThreadStateException. You must instantiate a completely new Thread object.
Q: What causes a thread to enter the WAITING state?
A: A thread enters the WAITING state if it calls methods that wait indefinitely for another thread’s action. The most common triggers are Object.wait() (waiting for someone to call notify()), Thread.join() (waiting for another thread to finish entirely), and LockSupport.park().