Thread Lifecycle
Each thread has a lifecycle consisting of thread states. Let’s understand these states.
- New
- Runnable
- Running
- Blocked/Waiting/Sleeping
- Terminated or Dead
New
When a thread object is created using new keyword, it is in a state that is called ‘New’ state. At this moment, only an object is created in the JVM. Please note that the thread hasn’t started working yet.
Runnable
Remember the statment t.start(); ? We used this to start a thread, right? So, does the thread start when this method is called on it? The answer is no. start() method call only ensures that the thread is registered in a pool of threads which is refered by the Thread scheduler to run a particular thread.
This thread pool is called Runnable pool, and the threads which are there in this pool are known to be in Runnable state.
In this state, thread is runnable, meaning it can be picked up by the thread scheduler to run any time. But the thread is still not running.
Running
A thread is said to be in this state when the thread is actully running its run() method code.
Blocked/Waiting/Sleeping
A thread which is running can be pushed to one of the three states: Blocked/Waiting/Sleeping.
Blocked state is the one in which a thread is blocked for some resource or a lock which is already acquired by another thread.
Waiting state is the one in which a thread goes after calling wait() method.
Sleeping state is the one in which a thread goes after calling sleep() method.
All these 3 states are clubbed as one state because they are more or less similar. In any of these states, the thread is not eligible for running.
Note -> Once a thread goes back from any of these states, it doesn’t start running immediately. Rather it goes back to runnable pool of threads where it is upto the scheduler when that thread will be picked to run.
Terminated or Dead
A thread goes to Terminated or Dead state when it completes its run() method execution. Once dead, a thread cannot be run again. If someone tries to start a dead thread, then an IllegalThreadStateException is thrown.