The Java Thread isAlive() method tests if this thread is alive. A thread is alive if it has been started and has not yet died.
DeclarationFollowing is the declaration for java.lang.Thread.isAlive() method
public final boolean isAlive()Parameters
NA
Return ValueThis method returns true if this thread is alive, false otherwise.
ExceptionNA
Example: Checking a thread being live using isAliveThe following example shows the usage of Java Thread isAlive() method. In this program, we've created a thread class ThreadDemo by implementing Runnable interface. In constructor, current thread is retrieved using currentThread() method and status of thread is printed using isAlive() method.
In main method, we've created a new thread of ThreadDemo class and started it using start() method. Then using join(), we've made the thread to wait till die. In the end again, its status is printed using isAlive() method.
package com.tutorialspoint; public class ThreadDemo implements Runnable { public void run() { Thread t = Thread.currentThread(); // tests if this thread is alive System.out.println("status = " + t.isAlive()); } public static void main(String args[]) throws Exception { Thread t = new Thread(new ThreadDemo()); // this will call run() function t.start(); // waits for this thread to die t.join(); // tests if this thread is alive System.out.println("status = " + t.isAlive()); } }Output
Let us compile and run the above program, this will produce the following result −
status = true status = falseExample: Checking a thread being live using isAlive with given Delay
The following example shows the usage of Java Thread isAlive() method. In this program, we've created a thread class ThreadDemo by implementing Runnable interface. In constructor, current thread is retrieved using currentThread() method and status of thread is printed using isAlive() method.
In main method, we've created a new thread of ThreadDemo class and started it using start() method. Then using join(), we've made the thread to wait till die. In the end again, its status is printed using isAlive() method.
package com.tutorialspoint; public class ThreadDemo implements Runnable { public void run() { Thread t = Thread.currentThread(); // tests if this thread is alive System.out.println("status = " + t.isAlive()); } public static void main(String args[]) throws Exception { Thread t = new Thread(new ThreadDemo()); // this will call run() function t.start(); // waits for this thread to die t.join(2000); // tests if this thread is alive System.out.println("status = " + t.isAlive()); } }Output
Let us compile and run the above program, this will produce the following result −
status = true status = false
java_lang_thread.htm
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4