A thread is alive or running if it has been started and has not yet died. To check whether a thread is alive use the isAlive()
method of Thread
class. It will return true
if this thread is alive, otherwise return false
.
package org.kodejava.lang;
public class ThreadAliveDemo implements Runnable {
public static void main(String[] args) {
Thread t1 = new Thread(new ThreadAliveDemo(), "FirstThread");
Thread t2 = new Thread(new ThreadAliveDemo(), "SecondThread");
// start the t1
t1.start();
// Check to see if the first thread is alive or not.
if (t1.isAlive()) {
System.out.format("%s is alive.%n", t1.getName());
} else {
System.out.format("%s is not alive.%n", t1.getName());
}
// Check to see if the second thread is alive or not.
// It should be return false because t2 hasn't been started.
if (t2.isAlive()) {
System.out.format("%s is alive.%n", t2.getName());
} else {
System.out.format("%s is not alive.%n", t2.getName());
}
}
public void run() {
System.out.println("Running [" +
Thread.currentThread().getName() + "].");
}
}
Latest posts by Wayan (see all)
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024