Home »
Java programming language
Java Thread Class final boolean isAlive() method with Example
Java Thread Class final boolean isAlive() method: Here, we are going to learn about the final boolean isAlive() method of Thread class with its syntax and example.
Submitted by Preeti Jain, on July 25, 2019
Thread Class final boolean isAlive()
- This method is available in package java.lang.Thread.isAlive().
- This method is used to find out whether a thread is alive or not so we need to know in which case a thread is alive if start() method has been called and the thread is not yet dead(i.e Thread is still in running state and not completed its execution).
- This method is not static so we cannot access this method with the class name too.
- The return type of this method is boolean so it returns true if the thread is alive (i.e. a thread is still running and not finished its execution yet) else return false (Thread will not be in running state and completed its execution ).
- This method does not raise an exception.
Syntax:
final boolean isAlive(){
}
Parameter(s):
We don't pass any object as a parameter in the method of the Thread.
Return value:
The return type of this method is boolean, it returns true if the thread is alive (i.e. a thread has been started by using start() method and has not yet died or terminated) else return false.
Java program to demonstrate example of isAlive() method
/* We will use Thread class methods so we are importing
the package but it is not mandate because
it is imported by default
*/
import java.lang.Thread;
class IsThreadAlive extends Thread {
public void run() {
try {
// this thread stops for few miliseconds before
// run() method complete its execution
Thread.sleep(500);
// Display status of Current Thread is alive
System.out.println("Is thread alive in run() method " + Thread.currentThread().isAlive());
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
}
public static void main(String[] args) {
// creating an object of class named
IsThreadAlive alive = new IsThreadAlive();
// Display status of thread is alive before
// calling start() method
System.out.println("Is thread alive before start() call:" + alive.isAlive());
alive.start();
// Display status of thread is alive after
// calling start() method
System.out.println("Is thread alive after start() call:" + alive.isAlive());
}
}
Output
E:\Programs>javac IsThreadAlive.java
E:\Programs>java IsThreadAlive
Is thread alive before start() call:false
Is thread alive after start() call:true
Is thread alive in run() method true