Table of contents
1.
Introduction
2.
What is Life Cycle Of A Thread?
3.
Stages of Life Cycle
4.
Flow Chart of Java Thread Life Cycle
5.
Implementation of Thread States
6.
Different Thread methods
7.
Java Program for Demonstrating Thread States
8.
More Examples on Thread Life Cycle
8.1.
Implementation 1
8.2.
Implementation 2
9.
Frequently Asked Questions
9.1.
Is Thread alive in Java?
9.2.
What is thread lifetime?
9.3.
What is a loop of thread?
9.4.
What is the purpose of thread?
10.
Conclusion
Last Updated: Jun 29, 2024
Easy

Life Cycle Of A Thread

Introduction

In this article, we will be learning about the life cycle of a thread, but before jumping on to the main concept, we shall take a look at what is a thread. A thread can be defined as the path or direction taken while executing the code. All programs have  At least one Thread, known as the main Thread, provided by the JVM. The thread allows the program to perform more efficiently by performing multiple tasks simultaneously.

Life Cycle Of A Thread

Must Read, Multithreading in java, Duck Number in Java and Hashcode Method in Java

What is Life Cycle Of A Thread?

The life cycle of a thread can be defined as the state transitions of a thread that starts from its birth till it ends. There are several life cycles in which a thread lies at any instant.

  • New
  • Runnable
  • Blocked
  • Waiting
  • Timed Waiting
  • Terminated

Stages of Life Cycle

  • New: When we create a new Thread object using the Thread class, a new thread starts its life cycle in the new state. The Thread which is born is known as Newborn State. This remains in this state until the program begins the Thread. With the help of the start() method, you can call the thread, otherwise, it might show some error.
     
  • Runnable: As soon as the start() method is called, the thread went from the New state into a runnable state. In this state, a thread has joined the queue of threads that are waiting for its execution.
     
  • Waiting: When a thread is in waiting mode, it waits for another thread to perform its task.
     
  • Timed Waiting: A runnable thread can transfer the timed waiting state for another to execute its task. 
     
  • Terminated(Dead): A thread moves into a dead state when the run() method completes its execution. A thread method can also be finished when the stop() method is called.
     
  • Blocked: When a thread is considered as blocked which means that it is suspended, sleeping, or waiting for little time in order to validate some conditions.

Flow Chart of Java Thread Life Cycle

Flow Chart of Java Thread Life Cycle

Implementation of Thread States

This represents the initial state of the Thread that is the NEW state

public static void final Thread.State NEW


This represents the Thread's runnable state, which means that the Thread is waiting in the queue to run.

public static void final Thread.State RUNNABLE


This represents the waiting state, which means waiting for another thread to complete its task.

public static void final Thread.State WAITING


This represents the timed waiting state. The critical difference between waiting and timed waiting is the time constraint.

public static void final Thread.State TIMED_WAITING


This represents the final state of a thread that is terminated. This means that it has completed its execution.

public static void final Thread.State TERMINATED


This represents the blocked state, which means that the threads are waiting for their chance to get locked.

public static void final Thread.State BLOCKED

Different Thread methods

Methods

 

Description

 

start()

 

This method will begin the Thread execution, and JVM calls the run() method on the Thread.
Sleep(int milliseconds)This method makes the thread sleep; hence the execution of the Thread will pause for milliseconds.

getName()

 

This function will return the name of the thread.
setPriority(int newpriority)This method will change the Thread's priority.
yield()This causes the current Thread and other threads to execute.

Java Program for Demonstrating Thread States

Here's a simple Java program that demonstrates the different states of a thread:

class ThreadStateDemo implements Runnable {
    public void run() {
        try {
            // Moving the thread to timed waiting state
            Thread.sleep(1000);
            System.out.println(Thread.currentThread().getName() + " is in timed waiting state.");
            // Moving the thread to waiting state
            synchronized (this) {
                wait();
                System.out.println(Thread.currentThread().getName() + " is resumed and in runnable state.");
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        ThreadStateDemo runnable = new ThreadStateDemo();
        Thread thread = new Thread(runnable);

        // New state
        System.out.println(thread.getName() + " is in new state.");

        // Runnable state
        thread.start();
        System.out.println(thread.getName() + " is in runnable state.");

        try {
            // Sleep to ensure the thread gets time to move to the timed waiting state
            Thread.sleep(200);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        // Moving the thread to blocked state by acquiring the monitor lock
        synchronized (runnable) {
            try {
                // Notify the thread to wake it up from the waiting state
                runnable.notify();
                // Sleep to ensure the thread gets time to move to the runnable state after being notified
                Thread.sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        // Terminated state
        try {
            thread.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(thread.getName() + " is in terminated state.");
    }
}

 

Output

Thread-0 is in new state.
Thread-0 is in runnable state.
Thread-0 is in timed waiting state.
Thread-0 is resumed and in runnable state.
Thread-0 is in terminated state.

 

Explanation:

  1. New State: The thread is created but not started yet. This is demonstrated by printing the thread state before calling start().
  2. Runnable State: When start() is called, the thread moves to the runnable state.
  3. Timed Waiting State: The thread moves to this state when it calls Thread.sleep(1000).
  4. Waiting State: The thread moves to this state when it calls wait() inside the run() method.
  5. Blocked State: The main thread acquires the monitor lock of the runnable object and calls notify().
  6. Runnable State: After being notified, the thread resumes execution.
  7. Terminated State: The thread moves to this state after the run() method completes its execution.

More Examples on Thread Life Cycle

Implementation 1

public class Ex28 extends Thread {
	public static void main(String[] args) {
		Ex28 thread = new Ex28();
		thread.start();
		System.out.println("This part of the code is running outside the thread");
	}
	public void run() {
		System.out.println("This part of the code is running inside a thread");
	}
}

 

Output

This part of the code is running outside the thread
This part of the code is running inside a thread


In this code, we have taken the simple example of Thread, and we have shown its execution. 

Practice by yourself on java online compiler.

Implementation 2

public class Ex29 implements Runnable 
{
	public static void main(String[] args) 
	{
		Ex29 obj = new Ex29();
		Thread thread = new Thread(obj);
		thread.start();
		System.out.println("This part of code is outside of the thread");
	}
	public void run() {
		System.out.println("This part of code is running in a thread");
	}
}

 

Output

This code is outside of the Thread
This code is running in a thread.

In this example, we have used the Thread's state, which is runnable, and we have clearly shown its execution.

Frequently Asked Questions

Is Thread alive in Java?

The Thread is not alive in Java. When we call the start() method on the Thread object, it changes to Runnable. Thus the control is transferred to the thread scheduler to finish its execution.

What is thread lifetime?

Thread lifetime refers to the duration from a thread's creation until its termination. It encompasses various states including new, runnable, running, blocked, waiting, timed waiting, and terminated, reflecting the thread's status during its execution.

What is a loop of thread?

A loop of thread involves repeatedly executing a block of code within a thread. This loop continues until a specified condition is met, allowing the thread to perform iterative tasks or continuously check for events or changes.

What is the purpose of thread?

The purpose of a thread is to enable concurrent execution within a program. Threads allow multiple tasks to run simultaneously, improving performance and responsiveness by utilizing multi-core processors and managing tasks independently.

Conclusion

In this blog, we have covered a topic on the life cycle of a thread. We gave a brief introduction to the life cycle of a thread and the different thread stages. We also discussed the implementation of different thread stages. We also discussed different types of thread methods. We also took a few examples explaining different thread stages.

If you want to know more about these topics, please visit our website, Guided Paths and solve more interview problems Problems.

Recommended Readings:

Live masterclass