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.

That’s all about Thread life cycle in java.

Multithreading docs.

https://docs.oracle.com/cd/E19455-01/806-5257/6je9h032e/index.html

Other multithreading tutorials.

The Runnable interface in java.
Thread Priority in Java with example.
Daemon thread in java with example.
Thread yield() method in java.
Thread sleep() method in java.
Thread join() method in java.
wait(),notify() and notifyAll() in java.
Difference between sleep() and wait() method in java.