The Lifecycle of a thread in Java

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:

  • NEW
  • RUNNABLE
  • BLOCKED
  • WAITING
  • TIMED_WAITING
  • TERMINATED

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.

Pictorial Representation

Explanation of States

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.

NEW

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.

Declaration: public static final Thread.State NEW

RUNNABLE

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.

Declaration: public static final Thread.State RUNNABLE

BLOCKED  

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.

Declaration: public static final Thread.State BLOCKED

WAITING

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.

Declaration: public static final Thread.State WAITING

TIMED_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.

Declaration: public static final Thread.State TIMED_WAITING

TERMINATED

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.

Declaration: 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.