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

Java 8Object Oriented ProgrammingProgramming

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
raja
Published on 12-Jan-2018 10:05:11
Advertisements