πŸŽ‰ Special Offer !    Code: GET300OFF    Flat β‚Ή300 OFF on every Java Course
Grab Deal πŸš€

isAlive() Method with Example  


Thread isAlive() Method
  • isAlive() method checks whether a thread is currently running or not.
  • If the thread has been started and not yet died, it will return true, otherwise it will return false.
  • Use :-
    • Determine if a thread is still executing for control or debugging purposes.
    • Avoid performing operations on threads that have already completed.
    • Useful for thread management in multi-threaded applications or thread pools.
  • Syntax :-
    • public final boolean isAlive()
  • Program :-
    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
        }
    }
  • Other key points :-
    • isAlive() returns true only after start() is called and before the thread dies.
    • It is final method, cannot be overridden.
    • It is useful for monitoring thread state in concurrent programs.
    • It does not block the calling thread β€” it simply returns the status.