Thread Lifecycle
During its lifetime, a thread in Java undergoes various states from its creation to its termination. Understanding these states is critical for writing robust multithreaded applications.
According to the java.lang.Thread.State enum, a thread can be in one of the following states:
- NEW
- RUNNABLE
- BLOCKED
- WAITING
- TIMED_WAITING
- TERMINATED
Visualizing the Lifecycle
The following state diagram illustrates how a thread transitions between different states:
Detailed Explanation of States
1. NEW
A thread is in the New state when an instance of the Thread class is created, but the start() method has not yet been invoked on it.
- At this point, the thread is an empty object; no system resources have been allocated.
2. RUNNABLE
When the start() method is called, the thread enters the Runnable state.
- In this state, the thread is either currently executing (Running) or is ready to run and waiting for its turn to get CPU time from the thread scheduler.
- Java does not distinguish between a "Ready" state and a "Running" state; both are considered
RUNNABLE.
3. BLOCKED
A thread enters the Blocked state when it is trying to enter a synchronized block or method, but the lock for that block/method is currently held by another thread.
- The thread will remain in the blocked state until it successfully acquires the monitor lock.
4. WAITING
A thread is in the Waiting state when it is waiting indefinitely for another thread to perform a particular action.
- A thread enters this state by calling methods like
Object.wait()(without timeout) orThread.join()(without timeout). - It will leave this state and return to
RUNNABLEonly when another thread callsnotify()ornotifyAll()on the same object, or when the thread it is joined with finishes execution.
5. TIMED_WAITING
A thread enters the Timed Waiting state when it is waiting for another thread to perform an action for up to a specified waiting time.
- A thread enters this state by calling methods like
Thread.sleep(milliseconds),Object.wait(milliseconds), orThread.join(milliseconds). - It returns to
RUNNABLEwhen the time expires or the specific condition is met (like a notification).
6. TERMINATED (Dead)
A thread enters the Terminated state when it has finished its execution (i.e., its run() method has completed normally) or if it was terminated abruptly due to an unhandled exception.
- Once a thread is terminated, it cannot be restarted. Calling
start()on a dead thread throws anIllegalThreadStateException.