Monday, March 5, 2012

How do I check if a thread is alive in Java?


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.

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());
        }
    }
}

No comments:

Post a Comment