×
☰ See All Chapters

Thread Life cycle in Java

thread-life-cycle-in-java-0
 

New state

When a thread instance/object is created, thread will be created and moved to “new” state.

Thread obj = new Thread(new MyRunnable()); //thread will be created and moved to “new” state.

Runnable state

When start() method is called, thread moves to runnable state.  A separate method call stack will be ceated with run method being at the bottom of the call stack.

obj.start(); // new moves to runnable state

A thread can also return to the “runnable state” after coming back from a running, sleeping, waiting or blocked state.

Running state

In running state, thread will be running, in fact code present inside run() method will be executing. A thread can move out of the “running state” to runnable, non-runnable or dead state for various reasons. Also we can move running thread to other state explicitly by calling yield(), sleep(), wait(), join or stop() method etc.

Non runnable state (Sleeping state, Waiting state and Blocked state)

A non-runnable thread is a paused thread because of certain reasons like unavailability of resources, waiting for another thread to finish, user explicitly paused etc...

When this non runnable thread is ready for re-run it will move to runnable state, but not to running state.

We have three types of non-runnable threads

  1. Sleeping state: A thread moves into the “sleeping state “when sleep() is called on a running thread. 

  2. Waiting state: A thread moves into the “waiting state” when wait() is called on a running Thread 

  3. Blocked state: A thread moves into the “blocked state” when join() is called or when a resource is not available. 

Dead state

When run method execution is completes, thread moves to dead state.

We can also call stop() or destroy() method explicitly to move a running thread into “dead state” but the methods have been deprecated.

Methods to change thread state

From state

To state

Method

Method Belongs to Which Class

New

Runnable

start();

class Thread

Runnable

Running

run();

class Thread

Running

Runnable

yield();

class Thread

Running

Dead

stop();

destroy();

class Thread

Running

Sleeping

sleep();

class Thread

Running

Waiting

wait();

class Thread

Running

Blocked

join();

class Thread

Waiting

Runnable

notify();

notifyAll();

class Object

(Object is also a class which is the super class of all class in java, we will study this class in later chapters)

join() method

The join() method waits for a thread to die. In other words, it causes the currently running threads to stop executing until the thread it joins with completes its task.

 


All Chapters
Author