Java Thread Lifecycle

Category: Java   Tags: Java, Java Thread, Java Multithread, Java Thread Lifecycle

A Java thread has its own life cycle and it can be only in one of five states:

  • New
  • Runnable
  • Running
  • Waiting or Sleeping
  • Terminate

Java thread life cycle

New

A thread will be in this state when Thread instance has been created, but the start() method has not been invoked on the thread.

In this state thread is considered not alive.

Runnable

A thread enters the runnable state when the start() method is invoked. When the thread is in the runnable state, it is considered alive. A thread can return back to this state from running, waiting or sleeping state.

Running

This is the state a thread is in when the thread scheduler selects it to be the currently executing process. A thread scheduler select a thread from the runnable pool.

Waiting or Sleeping

A thread is in this state when the thread is still alive, but is currently not eligible to run. A thread is in blocked state when it is waiting for a resource for example like I/O or an object's lock. Once those resources are available, thread is again available to be back in running state.

A thread is in sleeping state when a Java code call it to sleep some time and once that time is expired the thread is available to jump back to running state. sleep() method is used to push the thread to sleeping state.

Terminate

A thread is terminated when its run() method completes. Once a thread is dead, it can never be brought back to life. If you invoke start() on a dead Thread instance, you'll get a runtime exception.