Thread isAlive Java Example

Thread isAlive Java Example


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


Java Thread isAlive() Example
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
  1. A thread is said to be alive (where isAlive() returns true) when is has been started and still not died.
  2. isAlive() method returns true if the thread (upon which it is called) is still running and not finished.
  3. isAlive() checks if the thread is alive and executing.
  4. 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).
  5. isAlive() is used to know if a thread is actually started and not yet terminated its execution.
  6. 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

2 thoughts on “Thread isAlive Java Example

  1. Nikhil

    hello sir..
    you said that we need an object to call isAlive() method.
    Can you please elaborate what this line is doing in the above code?

    Thread t1 = Thread.currentThread();

    is this new thread same as (d1) thread ?
    Can we use this.isAlive() instead of creating new thread class object ?

Leave a Reply

Your email address will not be published. Required fields are marked *