Java Thread Life Cycle
In the previous chapter, we have already seen the basic introduction of the thread.
Contents
Life Cycle of a Thread :
When thread is created in java then undergoes different phases. The different states, phases of the thread are shown in the below diagram -
above mentioned stages are explained below -
Stage 1 : New Thread
- Each thread have very first stage called i.e new state
- Thread remains in the new state until the program starts the thread
- Thread in this stage is also called as born thread.
Stage 2 : Runnable State
- Running thread is in runnable state.
- When we start the new thread then that thread is started, the thread becomes runnable.
Stage 3 : Waiting State
- Sometimes thread goes into the waiting state, when the thread waits for another thread to perform certain action or task
- A thread goes back to the runnable state only when another thread sends signals to the waiting thread to continue execution
Stage 4 : Timed waiting State
- Sometimes running thread goes to Timed waiting State for particular interval of time
- Thread will again goes to running state after waiting specific interval expires.
Stage 5 : Terminated State
- After the compilation of the task running thread goes to terminated state
Example to illustrate the life-cycle of the thread :
Don’t bother about the syntax of the Thread at this moment. We will be learning the Thread creation in the next chapter.
This example is just to let you know the life cycle of the thread.
package com.c4learn.thread; public class ThreadDemo extends Thread { public void run() { System.out.println("Thread is running !!"); } public static void main(String[] args){ ThreadDemo t1 = new ThreadDemo(); ThreadDemo t2 = new ThreadDemo(); System.out.println("T1 ==> " + t1.getState()); System.out.println("T2 ==> " + t2.getState()); t1.start(); System.out.println("T1 ==> " + t1.getState()); System.out.println("T2 ==> " + t2.getState()); t2.start(); System.out.println("T1 ==> " + t1.getState()); System.out.println("T2 ==> " + t2.getState()); } }
Output :
T1 ==> NEW T2 ==> NEW T1 ==> RUNNABLE T2 ==> NEW T1 ==> RUNNABLE T2 ==> RUNNABLE Thread is running !! Thread is running !!
In the above example we are able to see the different states of the Java Thread.