A thread lifecycle is divided into five different states, which a thread may go through in its lifetime. Each thread can be in one of the following five states. Let's understand
each of these different states in the order in which they are mentioned below -:
Waiting or Blocked or Sleeping State.
A thread enters a new state when an object of Thread class is created but the start() method hasn't been called on it yet.
In new state, a thread is not considered alive as it's not a thread of execution. Once the start() method is called on the thread,
it leaves the new state and enters the next state but once it leaves
new state, it's impossible for it to return back to new state in its lifetime.
A thread enters a runnable state when the start() method has been called on it. It means, that a thread is eligible to
run, but it's not yet running, as the thread scheduler hasn't selected it to run. At one point of time, there could be multiple thread in a runnable state,
it's always the choice of thread scheduler to decide on which thread to move to the next state from runnable state. A thread in runnable state is
considered to be alive. A thread can return to a runnable state after coming back from a sleeping, waiting/blocked
or running state.
A thread enters a running state when the thread schedular has selected it to run(out of all the threads in a
thread pool). In this state, a thread starts executing the run() method and it is alive and kicking.
From the running state, a thread can enter into waiting/blocked state, runnable or the final dead state.
Let's depict these states too through a diagram -
Waiting or Blocked or Sleeping State
A thread enters a not runnable in three situations -:
When a thread has called wait() method on itself and it is waiting for the other thread to notify it or wake it up.
When the method sleep() is called on a thread, asking it to sleep for a duration.
When a thread has called the join() method on another thread, which makes the first thread wait until the another thread has finished its execution.
When a thread is waiting for an Input/Output resource to be free.
When a thread finds itself in any of the above mentioned three states, such events pushes the thread into a blocking/waiting or sleeping mode and the thread is no longer eligible to
run. In any of these states, the thread is still considered to be alive. When thread gets out of waiting, blocking or
sleeping state, it re-enters into runnable state.
This is the last state in a thread's lifetime. A thread enters the dead state after it has successfully
completed executing the run() method. At this situation, it is considered to be not alive and hence if you try to call start()
method on a dead thread, it raises IllegalThreadStateException(which we will read about in an upcoming article).