Java Thread isAlive() Method Tutorial

In this section, we will learn what the Thread isAlive() method is and how to use it in Java.

Java Thread isAlive() Method

A thread can be alive or dead. When calling a thread using the start() method, that thread will be alive as long as running the associated instructions. Now, the moment the work of that thread is done, the state of the thread will change and it becomes dead.

Now, using the isAlive() method, we can see if a method is alive or not.

Java Thread isAlive() syntax

public final boolean isAlive()

Java Thread isAlive() parameters

The method does not take an argument.

Java Thread isAlive() Return Value

The return value of this method is of type boolean. If the target thread was alive, the return value will be true, otherwise the value false will return.

Java Thread isAlive() Exception:

The method does not throw an exception.

Example: using isAlive() method

public class Main {

    public static void main(String[] args) {

        Thread thread = new Thread(()->{
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        },"Thread-One");
        thread.start();
        System.out.println("Is Thread-One live?: "+thread.isAlive());
        
    }

}

Output:

Is Thread-One live?: true

In this example, the `thread` that we’ve created went to sleep for about 3 seconds after calling the `start()` method. But still when called the `isAlive()` method on this thread, we can see the return value is true. This means, as long as there’s a work for a thread, calling the `isAlive()` method will return the value true.

Leave a Reply