The lifecycle of a thread is a transition from one state to another. In java, there is a total of 6 states, and a thread can exist in any of them at any phase. The states are:
The initial state is NEW, and the final state of the thread is TERMINATED. So, the lifecycle of a thread is its journey from NEW to TERMINATED.
In Java, Thread.getState()
is the method that is used to get the current state of the thread. The value of these states is available as the ENUM
constants of the class java.lang.Thread.State
.
When a new thread is created, it is in the NEW state. It signifies that the execution of the thread is yet to start. The thread is yet to run.
public static final Thread.State NEW
When a new thread is ready to run, it gets into the RUNNABLE state. It signifies that the thread is ready to run. The Scheduling algorithm applied to the scheduler is responsible to allot CPU resources to run for a specific time slot.
public static final Thread.State RUNNABLE
When a RUNNABLE thread is waiting for any Input/Output operation to complete, it shifts to the BLOCKED state. Upon availability, the scheduler brings the BLOCKED thread back to the RUNNABLE thread. No CPU cycle is consumed in this state.
public static final Thread.State BLOCKED
When a RUNNABLE thread yet to complete all its process, waits for another thread on a specific condition. It goes into the WAITING state. Upon fulfillment of the condition, the WAITING thread resumes by again going to the RUNNABLE state. No CPU cycle is consumed in this state.
public static final Thread.State WAITING
When a RUNNABLE thread calls a method with a time out parameter, it goes into TIMED_WAITING state. Upon completion of the timeout/notification received, the TIMED_WAITING state is shifted again to the RUNNABLE state.
public static final Thread.State TIMED_WAITING
When a RUNNABLE thread gets into the TERMINATED state regardless of normal execution or any exception. This marks the last and final state of a thread. No CPU cycle is consumed in this final state.
public static final Thread.State TERMINATED
This was all about the life cycle of a thread. We will learn to create threads in the next lecture.