How to use isAlive() method of Thread class in Java?


The isAlive() method of the Thread class returns true if the thread is alive, which is anytime after the thread has been started but before it runs to completion.

Example

class first implements Runnable {
   public void run() {
      try {
         for(int i=0; i<=20; i+=2) {
            Thread.sleep(600); System.out.println(i);
         }
      } catch(Exception e) {
   }
}

class MyThread {
   public static void main(String args[]) {
      first obj = new first();
      Thread thread = new Thread(obj);
      thread.setPriority(Thread.MAX_PRIORITY);
      thread.start();
      System.out.println(thread.isAlive());
   }
}

Output

true
0
2
4
6
8
10
12
14
16
18
20

Sharon Christine
Sharon Christine

An investment in knowledge pays the best interest

Updated on: 20-Feb-2020

205 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements