Thread life cycle in Java

In this post, we will see Thread life cycle in Java. There are five states of a thread as below.

  1. New
  2. Runnable
  3. Running
  4. Non-Runnable (Waiting)
  5. Dead

New – The thread is in new state if you create an object of Thread class.

 

package multithreading;

class Thread1 extends Thread {

}

public class ThreadLifeCycleExample {

	public static void main(String[] args) {

		Thread1 thread = new Thread1();

	}

}

 

Runnable – The thread is in the runnable state after the invocation of start() method, but the thread scheduler has not selected it to be the running thread.

 

package multithreading;

class Thread1 extends Thread {

}

public class ThreadLifeCycleExample {

	public static void main(String[] args) {

		Thread1 thread = new Thread1();
		thread.start();

	}

}

 

Running – The thread is in running state if the thread scheduler has selected it. Now run() method will be invoked.


package multithreading;

class Thread1 extends Thread {

	public void run() {
		for (int i = 0; i < 5; i++) {

			System.out.println("Thread1 is in running state with name: - " + Thread.currentThread().getName());

		}

	}
}

public class ThreadLifeCycleExample {

	public static void main(String[] args) {

		Thread1 thread = new Thread1();
		thread.start();

	}

}

 

Non-Runnable (Waiting) – This is the state when the thread is in waiting state.

 

package multithreading;

class Thread1 extends Thread {

	public void run() {
		for (int i = 0; i < 5; i++) {

			System.out.println("Thread1 is in running state with name: - " + Thread.currentThread().getName());
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {

				e.printStackTrace();
			}
		}

	}
}

public class ThreadLifeCycleExample {

	public static void main(String[] args) throws InterruptedException {

		Thread1 thread = new Thread1();
		thread.start();
		

	}

}

 


Dead- A thread is in the terminated or dead state when it’s run() method exits.