A Programmer may create hundreds of threads of which some may be in born state, some in runnable state, some in blocked state and some in dead state (all these are known as life cycle methods). He would like to know which thread is still running in the process. The answer is isAlive() method defined in Thread class. It is an instance method (not static) and thereby should be called with a thread object only. The isAlive() method returns true if the thread is in runnable state or blocked state else returns false.
Following is the method signature as defined in Thread class
public final native boolean isAlive();
Following is a simple Java Thread isAlive() Example
public class Demo extends Thread
public void run()
Thread t1 = Thread.currentThread();
System.out.println("From run, status = " + t1.isAlive());
public static void main(String args)
Demo d1 = new Demo();
System.out.println("From main, status = " + d1.isAlive());
Output screen of Java Thread isAlive() Example
In the above code, d1 thread of Demo class is created and started. In the run() method t1 refers the current thread that is right now executing the run() method. Obviously, it is d1 as d1 is calling the run() method. The status of d1 in run() is true and in main() method is false. Calling join() waits the parent thread main not to die until the child d1 dies.
Some more definitions on Java Thread isAlive() Example
- A thread is said to be alive (where isAlive() returns true) when is has been started and still not died.
- isAlive() method returns true if the thread (upon which it is called) is still running and not finished.
- isAlive() checks if the thread is alive and executing.
- The Thread class comes with an instance method (that is to be called with an object) isAlive() to determine whether the thread is in born state or dead state where calling isAlive() returns false (here, isAlive() informs the thread is not running now or stopped).
- isAlive() is used to know if a thread is actually started and not yet terminated its execution.
- isAlive() is very less used and more common is join() usage.
Note: Java does not have a method to determine whether the thread is in born state or dead state.
For more on join(), read join() method with Example and Explanation