isAlive() method of Thread Class in Java programming

JavaObject Oriented ProgrammingProgramming

The isAlive function − It is used to check if a thread is alive or not. Alive refers to a thread that has begun but not been terminated yet. When the run method is called, the thread operates for a specific period of time after which it stops executing.

Syntax

final Boolean isAlive()

The above returns true if the thread on which the function is called is running and hasn’t been terminated yet. It returns false otherwise.

Let us see an example −

Example

 Live Demo

public class Demo extends Thread{
   public void run(){
      System.out.println("sample ");
      try{
         Thread.sleep(25);
      }
      catch (InterruptedException ie){
      }
      System.out.println("only ");
   }
   public static void main(String[] args){
      Demo my_obj_1 = new Demo();
      Demo my_obj_2 = new Demo();
      my_obj_1.start();
      System.out.println("The first object has been created and started");
      my_obj_2.start();
      System.out.println("The first object has been created and started");
      System.out.println(my_obj_1.isAlive());
      System.out.println("The isAlive function on first object has been called");
      System.out.println(my_obj_2.isAlive());
      System.out.println("The isAlive function on second object has been called");
   }
}

Output

The first object has been created and started
sample
The first object has been created and started
sample
true
The isAlive function on first object has been called
true
The isAlive function on second object has been called
only
only

A class named Demo extends the Thread class. Here, a ‘run’ function is defined wherein a try catch block is defined. Here, in the try block, the sleep function is called and the catch block is left empty. In the main function, two instances of the Demo object are created. The first object is stated and it is checked whether it is running or basically in runnable state using the ‘isAlive’ function. The same is done with the second object as well.

raja
Published on 04-Jul-2020 08:46:49
Advertisements