isAlive()
method checks whether a thread is currently running or not.
true
, otherwise it will return false
.
public final boolean isAlive()
class MyTask extends Thread
{
@Override
public void run()
{
System.out.println(getName() + " is running.");
for (int i = 1; i <= 5; i++)
{
System.out.println(getName() + " count: " + i);
}
System.out.println(getName() + " finished execution.");
}
}
public class IsAliveSimpleDemo
{
public static void main(String[] args) throws Exception
{
MyTask t1 = new MyTask();
t1.setName("Thread-1");
System.out.println("Before start: " + t1.isAlive()); // false
t1.start();
System.out.println("After start: " + t1.isAlive()); // true (likely)
// pause thread for 1 second
Thread.sleep(1000);
System.out.println("After completion: " + t1.isAlive()); // false
}
}
Before start: false After start: true Thread-1 is running. Thread-1 count: 1 Thread-1 count: 2 Thread-1 count: 3 Thread-1 count: 4 Thread-1 count: 5 Thread-1 finished execution. After completion: false
isAlive()
returns true
only after start()
is called and before the thread dies.
Your feedback helps us grow! If there's anything we can fix or improve, please let us know.
Weβre here to make our tutorials better based on your thoughts and suggestions.