Java Thread isAlive()

In this guide, you will learn about the Thread isAlive() method in Java programming and how to use it with an example.

1. Thread isAlive() Method Overview

Definition:

The Thread.isAlive() method tests if the thread is alive. A thread is considered alive if it has been started and has not yet died (either by completing its run method or by being explicitly stopped).

Syntax:

public final boolean isAlive()

Parameters:

- None.

Key Points:

- The method returns true if the thread is still running; otherwise, it returns false.

- It doesn't determine whether the thread is currently executing; a thread could be alive but waiting due to synchronization or other reasons.

- The isAlive() method can be particularly useful when monitoring or waiting for the completion of threads.

2. Thread isAlive() Method Example

public class ThreadIsAliveExample {
    public static void main(String[] args) {
        Thread exampleThread = new Thread(() -> {
            try {
                System.out.println("Thread is starting...");
                Thread.sleep(3000);  // Sleep for 3 seconds
                System.out.println("Thread is ending...");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        System.out.println("Before start: Is thread alive? " + exampleThread.isAlive());

        exampleThread.start();

        System.out.println("After start: Is thread alive? " + exampleThread.isAlive());

        // Give the thread a moment to complete
        try {
            exampleThread.join();
        } catch (InterruptedException ignored) {}

        System.out.println("After completion: Is thread alive? " + exampleThread.isAlive());
    }
}

Output:

Before start: Is thread alive? false
After start: Is thread alive? true
Thread is starting...
Thread is ending...
After completion: Is thread alive? false

Explanation:

In the example, we create a exampleThread that just sleeps for 3 seconds. Before starting the thread, the isAlive() method returns false. After starting, but before it completes, the method returns true. Once the thread has completed its run, the method again returns false. The output of the program demonstrates these changes in the alive status of the thread.

Comments