How do I check if a thread is alive?

A thread is alive or runningn if it has been started and has not yet died. To check whether a thread is alive use the isAlive() method of Thread class. It will return true if this thread is alive, otherwise return false.

package org.kodejava.example.lang;

public class ThreadAlive implements Runnable {

    ThreadAlive() {
    }

    public void run() {
        System.out.println("Running [" +
                Thread.currentThread().getName() + "].");
    }

    public static void main(String[] args) {
        Thread t1 = new Thread(new ThreadAlive(), "FirstThread");
        Thread t2 = new Thread(new ThreadAlive(), "SecondThread");

        // start the t1
        t1.start();

        //
        // Check to see if the first thread is alive or not.
        //
        if (t1.isAlive()) {
            System.out.format("%s is alive.%n", t1.getName());
        } else {
            System.out.format("%s is not alive.%n", t1.getName());
        }

        //
        // Check to see if the second thread is alive or not.
        // It should be return false because t2 hasn't been started.
        //
        if (t2.isAlive()) {
            System.out.format("%s is alive.%n", t2.getName());
        } else {
            System.out.format("%s is not alive.%n", t2.getName());
        }
    }
}
Wayan Saryada

Wayan Saryada

A programmer, runner, recreational diver, currently living in the island of Bali, Indonesia. Mostly programming in Java, creating web based application with Spring Framework, JPA, etc. If you need help on Java programming you can hire me on Fiverr.
Wayan Saryada

Leave a Reply