Understanding Thread Lifecycle

Tutorial 3 of 5

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.