Java / Java Multithreading and Concurrency

Understanding Thread Lifecycle

In this tutorial, you will learn about the lifecycle of a thread in Java. You'll gain a deep understanding of different thread states and how a thread transitions from one state t…

Tutorial 3 of 5 5 resources in this section

Section overview

5 resources

Introduces multithreading concepts to enable concurrent execution.

Understanding Thread Lifecycle in Java

1. Introduction

In this tutorial, we'll delve into the lifecycle of a thread in Java. Threads are crucial in Java to execute multiple tasks simultaneously. Understanding their lifecycle is pivotal for efficient multithreading programming.

By the end of this tutorial, you will:
- Understand the different states of a thread.
- Learn how a thread moves from one state to another.
- Get hands-on experience with practical examples.

Prerequisites:
Basic knowledge of Java and object-oriented programming concepts.

2. Step-by-Step Guide

In Java, a thread goes through various stages in its lifecycle. These stages include:

  • New: The thread is in the new state if you create an instance of Thread class but before the invocation of start() method.
  • Runnable: The thread is in runnable state after invocation of start() method, but the thread scheduler has not selected it to be the running thread.
  • Running: The thread is in running state if the thread scheduler has selected it.
  • Non-Runnable (Blocked): This is the state when the thread is still alive, but is currently not eligible to run.
  • Terminated: A thread is in terminated or dead state when its run() method exits.

Thread Transitions

  • New to Runnable: When we call the start() method.
  • Runnable to Running: When the scheduler selects the thread.
  • Running to Non-Runnable: When the thread is waiting for a resource, sleeping, or blocked on I/O. This is typically achieved using methods like sleep(), wait(), etc.
  • Non-Runnable to Runnable: When the thread's wait time is over, or the resource it is waiting for is free.
  • Running to Dead: When the thread's run() method completes.

3. Code Examples

Example 1: Thread creation and starting it

class MyThread extends Thread {
    public void run() {
        System.out.println("Thread is running"); 
    }
}

public class Main {
    public static void main(String args[]) {
        MyThread t1=new MyThread(); // Thread is in New state
        t1.start(); // Thread moved to Runnable state
    }
}

In the above example, t1 is a thread which is in new state initially. After calling the start() method, it moves to the Runnable state and starts executing the run() method.

Expected Output

Thread is running

Example 2: Moving thread to Non-Runnable state

class MyThread extends Thread {
    public void run() {
        try {
            Thread.sleep(500); // Thread moved to Non-Runnable state
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("Thread is running");
    }
}

public class Main {
    public static void main(String args[]) {
        MyThread t1=new MyThread(); 
        t1.start();
    }
}

In this example, the thread t1 is put to sleep for 500 milliseconds, hence it moves to Non-Runnable state. After the sleep time is over, it moves back to Runnable state and prints "Thread is running".

Expected Output

Thread is running

4. Summary

In this tutorial, we've learned about the lifecycle of a thread in Java. We've looked at different states a thread can have and how a thread transitions from one state to another.

For further learning, you can explore more about thread synchronization and inter-thread communication in Java.

5. Practice Exercises

Exercise 1: Create a thread and move it to the Non-Runnable state by making it wait for a specific resource.

Exercise 2: Create multiple threads and observe their execution. Use methods like sleep() and wait() to move threads between different states.

Solutions:

Here are the solutions but try to solve them on your own before looking at these.

Exercise 1:

class MyThread extends Thread {
    public void run() {
        synchronized(this){
            try {
                wait(); // Thread will move to Non-Runnable state
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

public class Main {
    public static void main(String args[]) {
        MyThread t1=new MyThread(); 
        t1.start();
    }
}

Exercise 2:

class MyThread extends Thread {
    public void run() {
        for (int i = 0; i < 5; i++) {
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getId() 
                               +" Value "+ i);
        }
    }
}

public class Main {
    public static void main(String args[]) {
        MyThread t1=new MyThread(); 
        t1.start();

        MyThread t2=new MyThread(); 
        t2.start();
    }
}

In this example, we are creating two threads. Both threads will execute simultaneously and print the values from 0 to 4 with a delay of 500 milliseconds between each print.

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

Markdown to HTML Converter

Convert Markdown to clean HTML.

Use tool

Color Palette Generator

Generate color palettes from images.

Use tool

Countdown Timer Generator

Create customizable countdown timers for websites.

Use tool

Percentage Calculator

Easily calculate percentages, discounts, and more.

Use tool

Time Zone Converter

Convert time between different time zones.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help