Turn Desktop View Off
by Dinesh Thakur

In order to make sure that the main thread finishes last, we introduced a long enough delay by calling the sleep () method within the main() method so that all other threads finish before the main thread. But this of course is hardly a satisfactory solution because if your estimate for the time delay is too short then other threads could finish after the main thread finishes. Therefore, the Thread class provide method isAli ve ()  to determine if a thread has ended .

• final boolean isAlive (): The isAlive () method returns true if the invoking thread is alive. A thread is considered alive when the thread's start () method has been called and thread is not yet dead. Otherwise, it returns false.

class MyThread extends Thread

{
    double e ;
    public void run()
    {
        for(int i=0;i<15;i++)
            {
                  e += 1.0/factorial(i);
             }
    }
    int factorial(int n)
    {
        if(n==0)
            return(1);
       else
            return(n * factorial(n-1));
     }
}
   public class isAliveEx
   {
        public static void main (String[] args)
       {
                  System.out .println("Main Thread Starts");
                  MyThread t1 = new MyThread();
                  t1.setName("Factorial Calculation Thread");
                  t1.start();
                  System.out.println(t1.getName() + " is alive = " + t1.isAlive());
                  while(t1.isAlive())
                       {
                            try
                             {
                                 Thread.sleep(100);
                             }
                             catch(InterruptedException ex)
                             {
                                   ex.printStackTrace();
                             }
                       }
                       System.out.println("The Value of e ="+t1.e);
                       System.out.println(t1.getName()+" is alive = " +t1.isAlive());
                       System.out.println("Main Thread Ends");
       }   
  }

isAlive() in Java Example