Life Cycle of a Thread in JAVA

Life Cycle of a Thread in JAVA

threadlifecycle

Thread States

1. New

A newly created thread object instance on which the start() method has not yet been invoked(not yet started execution) is in the new state. To learn how to instantiate threads you can check this tutorial.

2. Runnable

A thread in New state enters the Runnable state when the start() method is invoked on it. There are 2 important points to note regarding the runnable state –

  1. When the thread enters the runnable state after invoking the start() method, it is not necessary that the thread immediately starts executing. A thread runs when the logic it holds in its method can be executed by the processor. In case the thread logic needs any resource which is not available then the thread waits for the resource to become available.
  2. A thread in runnable state may run for some time and then get blocked or may enter the waiting or timed_waiting states.

3. Blocked

A thread enters the blocked state waiting for a monitor lock to be released.

4. Waiting

A thread enters into the waiting state when the thread is waiting for some other thread to perform a particular action without any time limit. For example, calling the join() method, may make a thread enter into the waiting state.

5. Timed_Waiting

A thread enters into the timed_waiting state when the thread is waiting for some other thread to perform a specific action for a specified time period. For example calling Thread.sleep(1000) for 1 second, may make a thread enter into timed_waiting state.

6. Terminated

A thread enters the terminated state when the thread has finished execution.

Below are Programs showing how a thread enters each state

1. New

A NEW Thread (or a Born Thread) is a thread that has been created but not yet started. It remains in this state until  start()method is invoked.

Program(Save as Main.java)
class ThreadLifeCycle implements Runnable
{
    public void run(){}
}
class Main
{
    public static void main(String args[])
    { 
        ThreadLifeCycle tlc = new ThreadLifeCycle();
        Thread t = new Thread(tlc);
        System.out.println("Thread State : "+t.getState());
    }
}
Output
javac Main.java
java Main
Thread State : NEW

In the above program as we have not started the mentioned thread(not called the start() method), but just created it, the method t.getState() prints NEW.

2. Runnable

When we have created a new thread and called the start() method, the state of the thread is moved from NEW to RUNNABLE state. Threads in this state are either running or ready to run, but they are re waiting for resource allocation from the system.

Program(Save as Main.java)
class ThreadLifeCycle implements Runnable
{
    public void run(){}
}

class Main
{
    public static void main(String args[])
    {
        ThreadLifeCycle tlc = new ThreadLifeCycle();
        Thread t = new Thread(tlc);
        t.setName("Thread(1)");
        t.start();
        System.out.println(t.getName()+" State : "+t.getState());
    }
}
Output
javac Main.java
java Main
Thread(1) State : RUNNABLE

In the above program, as soon as the start() method is called, the thread moves from NEW to RUNNABLE state, but the output may not always be RUNNABLE as when the control of the program reaches the print statement, the thread might have already finished execution, hence we might get Terminated as output,as all this depends on the thread scheduler.

3. Blocked

A thread enters this state when it is waiting for a monitor lock and is trying to access a section of code that is locked by some other thread.

Program(Save as Main.java)
class ThreadLifeCycle implements Runnable
{
    Thread t2;
    ThreadLifeCycle(){
        t2 = new Thread(this);
    }
    public synchronized void run(){
        String name = Thread.currentThread().getName();
        String state = Thread.currentThread().getState().toString();
        System.out.println(name+" is inside run() of class ThreadLifeCycle and state = "+state); 
        for(int i=1;i<=3;i++)
        {
           if(Thread.currentThread().getName().equals("Thread(1)"))
               System.out.println(t2.getName()+" is "+t2.getState());
           System.out.println(" value = "+i);
           try{
               Thread.sleep(1000); 
           }
          catch(InterruptedException ie){}
        }
    }   
}
class Main
{
    public static void main(String args[]) throws InterruptedException
    { 
        ThreadLifeCycle tlc = new ThreadLifeCycle();
        Thread t1 = new Thread(tlc);
        t1.setName("Thread(1)");
        tlc.t2.setName("Thread(2)");
        t1.start(); 
        Thread.sleep(100);
        tlc.t2.start();
    }
}
Output
javac Main.java
java Main
Thread(1) is inside run() method and state = RUNNABLE
Thread(2) is NEW
value = 1
Thread(2) is BLOCKED
value = 2
Thread(2) is BLOCKED
value = 3
Thread(2) is inside run() method and state = RUNNABLE
value = 1
value = 2
value = 3

In the above program, we have used the synchronized keyword next to void run() method, indicating that once a thread enters the run() method, no other thread can enter the run() method till the previous thread has finished execution. Hence, once thread(1) enters the run() method, thread(2) cannot enter the run() method till thread(1) has completed its execution, therefore the state of thread(2) is blocked as it is waiting for the lock to be released by thread(1) on run() method. As soon as thread(1) completes its execution thread(2) enters the run() method and state changes to runnable.

4. Waiting

A thread is in the WAITING state when it waits for another thread on a condition. When this condition is fulfilled, the scheduler is notified and the waiting thread is moved to runnable state. There is no timeout period defined in join() or wait() methods.

A thread can enter this state by calling any one of following three methods:

  1. Thread.join()
  2. object.wait()
  3. LockSupport.park()
Program(Save as Main.java)
class ThreadLifeCycle implements Runnable
{ 
    public void run()
    {
        String name = Thread.currentThread().getName();
        String state = Thread.currentThread().getState().toString();
        System.out.println(name+" is inside run() of class ThreadLifeCycle and state = "+state); 
        try{
            Thread.sleep(1000);
        }
        catch(InterruptedException ie){}
        System.out.println(Main.t1.getName()+" is in "+Main.t1.getState()+" state");
    }
}
class Main implements Runnable
{
    public static Thread t1;
    public static void main(String args[]) throws InterruptedException
    {
        Main m = new Main();
        t1 = new Thread(m);
        t1.setName("Thread(1)");
        t1.start();
    }
    public void run()
    {
        ThreadLifeCycle tlc = new ThreadLifeCycle();
        Thread t2 = new Thread(tlc);
        t2.setName("Thread(2)");
        t2.start();
        String name = Thread.currentThread().getName();
        String state = Thread.currentThread().getState().toString();
        System.out.println(name+" is inside run() of class Main and state = "+state);
        try{
            t2.join();
        }
        catch(InterruptedException ie){}
    }
}
Output
javac Main.java
java Main
Thread(2) is inside run() of class ThreadLifeCycle and state = RUNNABLE
Thread(1) is inside run() of class Main and state = RUNNABLE
Thread(1) is in WAITING state

In the above program, we have created two threads, thread(1) and thread(2). The execution of a program in JAVA always starts from main() method, hence when t1.start() is called, it enters into run() method of main. On entering the run() method in main, we are creating a new thread called thread(2). On calling t2.start(), the program control switches to run() method of ThreadLifeCycle class class where t2.join() is called, which means that thread(1) should not be executed till thread(2) finishes its execution, hence the state of thread(1) is WAITING inside ThreadLifeCycle class after the t2.join() method is called.

5. Timed_Waiting

A thread enters in the Timed_Waiting state when it is waiting for another thread to perform some action. A thread lies in this state until the timeout is completed or until a notification is received. There is timeout parameter defined with the methods.

A thread can enter Timed_Waiting state by calling any one of following 5 methods:

  1. wait(int timeout)
  2. Thread.sleep(long millis)
  3. thread.join(long millis)
  4. LockSupport.parkNanos
  5. LockSupport.parkUntil
Program(Save as Main.java)
class ThreadLifeCycle implements Runnable
{ 
    public void run()
    {
        try{
            Thread.sleep(3000);
        }
        catch(InterruptedException ie){}
    }
}

class Main
{
    public static Thread t1;
    public static void main(String args[]) throws InterruptedException
    {
        ThreadLifeCycle tlc = new ThreadLifeCycle();
        Thread t1 = new Thread(tlc);
        t1.setName("Thread(1)");
        t1.start();
        Thread.sleep(1000);
        System.out.println(t1.getName()+" in main and is in "+t1.getState()+" state");
    }
}
Output
javac Main.java
java Main
Thread(1) in main and is in TIMED_WAITING state

In the above program, thread(1) enters into Timed_Waiting state when sleep() method is called with a timeout period. When t1.start() method is called the thread(1) enters into the run() method and executes Thread.sleep(3000), which means thread(1) is put to sleep for 3 seconds, while the Thread.sleep(1000) method inside main method is to make sure that the print statement executed after it, ensures that the thread has executed Thread.sleep(3000) method inside run() method, to display the output as Timed_Waiting state.

6. Terminated

A thread is in Terminated state when a thread has finished execution or terminated abnormally.

Program(Save as Main.java)
class ThreadLifeCycle implements Runnable
{ 
    public void run()
    {
        try{
            Thread.sleep(10);
        }
        catch(InterruptedException ie){}
    }
}
class Main
{
    public static void main(String args[]) throws InterruptedException
    {
        ThreadLifeCycle tlc = new ThreadLifeCycle();
        Thread t1 = new Thread(tlc);
        t1.setName("Thread(1)");
        t1.start();
        Thread.sleep(1000);
        System.out.println(t1.getName()+" in main and is in "+t1.getState()+" state");
    }
}
Output
javac Main.java
java Main
Thread(1) in main and is in TERMINATED state

In the above program, when t1.start() method is called the thread executes the run() method the Thread.sleep(10) makes thread(1) sleep for 0.01 seconds while the Thread.sleep(1000) inside main is to ensure that by the time control of the program reaches print statement, the thread created(t1) has finished execution, hence we get the output of thread(1) as Terminated.

Share Me!