Java Thread check thread alive state

Introduction

We can use isAlive() from Thread to check if a thread is running.

Its general form is shown here:

final boolean isAlive() 

The isAlive() method returns true if the thread upon which it is called is still running.


// Using join() to wait for threads to finish.
class MyThread implements Runnable {
  String name; // name of thread
  Thread t;//from  w w w.j a va  2  s. co m

  MyThread(String threadname) {
    name = threadname;
    t = new Thread(this, name);
    System.out.println("New thread: " + t);
    t.start(); // Start the thread
  }

  // This is the entry point for thread.
  public void run() {
    try {
      for (int i = 5; i > 0; i--) {
        System.out.println(name + ": " + i);
        Thread.sleep(1000);
      }
    } catch (InterruptedException e) {
      System.out.println(name + " interrupted.");
    }
    System.out.println(name + " exiting.");
  }
}

public class Main {
  public static void main(String args[]) {
    MyThread thread1 = new MyThread("One");

    System.out.println("Thread One is alive: " + thread1.t.isAlive());
    // wait for threads to finish
    try {
      System.out.println("Waiting for threads to finish.");
      thread1.t.join();
    } catch (InterruptedException e) {
      System.out.println("Main thread Interrupted");
    }

    System.out.println("Thread One is alive: " + thread1.t.isAlive());
    System.out.println("Main thread exiting.");
  }
}



PreviousNext

Related