Java Thread isAlive Example

In this article, we will learn java.lang.Thread class provides isAlive() method to test if this thread is alive or not. A thread is alive if it has been started and has not yet died.

Thread isAlive Method Example

  1. Let's create two threads
final Thread thread1 = new Thread(new MyTask());
final Thread thread2 = new Thread(new MyTask());
  1. Before starting the threads with start() method, just print to check whether the threads are alive or not.
System.out.println("Thread1 is alive? " + thread1.isAlive());
System.out.println("Thread2 is alive? " + thread2.isAlive());
  1. Start the threads and check again to check whether the threads are alive or not
thread1.start();
thread2.start();

while (thread1.isAlive() || thread2.isAlive()) {
     System.out.println("Thread1 is alive? " + thread1.isAlive());
     System.out.println("Thread2 is alive? " + thread2.isAlive());
     Thread.sleep(500l);
}
Let's put all together and the complete program is:
public class CheckIfThreadIsAliveUsingThreadAPI {

    public static void main(final String[] args) throws InterruptedException {

         System.out.println("Thread main started");

         final Thread thread1 = new Thread(new MyTask());
         final Thread thread2 = new Thread(new MyTask());

         System.out.println("Thread1 is alive? " + thread1.isAlive());
         System.out.println("Thread2 is alive? " + thread2.isAlive());

         thread1.start();
         thread2.start();

         while (thread1.isAlive() || thread2.isAlive()) {
              System.out.println("Thread1 is alive? " + thread1.isAlive());
              System.out.println("Thread2 is alive? " + thread2.isAlive());
              Thread.sleep(500l);
         }

         System.out.println("Thread1 is alive? " + thread1.isAlive());
         System.out.println("Thread2 is alive? " + thread2.isAlive());
  
         System.out.println("Thread main finished");
    }
}

class MyTask implements Runnable {
     @Override
     public void run() {
          for (int i = 0; i < 5; i++) {
              System.out.println("[" + Thread.currentThread().getName() + "] Message " + i);
              try {
                   Thread.sleep(200);
              } catch (final InterruptedException e) {
               e.printStackTrace();
              }
          }
     }
}
Output:
Thread main started
Thread1 is alive? false
Thread2 is alive? false
Thread1 is alive? true
Thread2 is alive? true
[Thread-0] Message 0
[Thread-1] Message 0
[Thread-1] Message 1
[Thread-0] Message 1
[Thread-1] Message 2
[Thread-0] Message 2
Thread1 is alive? true
Thread2 is alive? true
[Thread-0] Message 3
[Thread-1] Message 3
[Thread-1] Message 4
[Thread-0] Message 4
Thread1 is alive? false
Thread2 is alive? false
Thread main finished

Comments