by BehindJava
What is isAlive method used for in MultiThreading Java
In this tutorial we are going learn about isAlive method in MultiThreading.
Thread.isAlive()
-
The isAlive() method of thread class tests if the thread is alive. A thread is considered alive when the start() method of thread class has been called and the thread is not yet dead. This method returns true if the thread is still running and not finished.
public class Counter extends Thread { @Override public void run() { for (int i = 0; i <= 5; i++) { System.out.println(i + " Running Thread"); try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } public static void main(String args[]) { Counter c1 = new Counter(); System.out.println("Before starting thread isAlive: " + c1.isAlive()); c1.start(); System.out.println("After starting thread isAlive: " + c1.isAlive()); } }
Output:
Before starting thread isAlive: false After starting thread isAlive: true 0 Running Thread 0 Running Thread 1 Running Thread 1 Running Thread 2 Running Thread 2 Running Thread 3 Running Thread 3 Running Thread 4 Running Thread 4 Running Thread 5 Running Thread