Page 164 - CTS - CSA TP - Volume 2
P. 164

COMPUTER SOFTWARE APPLICATION - CITS




           Output:















            3  isAlive() Method:
              •  Purpose: Tests if a thread is alive.

              •  Syntax:isAlive()
              •  Return Type:boolean
              •  Use Case:
              •  Allows you to check if a thread has been started and has not yet completed its execution.
              •  Useful when you want to perform actions in the main thread after ensuring that another thread has finished.

           class IsAliveExample extends Thread {
               public void run() {
                   System.out.println(“Thread is running...”);
               }

               public static void main(String args[]) throws InterruptedException {
                   IsAliveExample isAliveThread = new IsAliveExample();
                   isAliveThread.start();
                   System.out.println(“Is thread alive? “ + isAliveThread.isAlive());
               }
           }

           Explanation:
           1  IsAliveExample Class:
           •  This class extends the Thread class, indicating that instances of this class can be executed as separate
              threads.
           2  run() Method:
           •  The run() method overrides the run() method of the Thread class, defining the behavior of the thread when it
              starts.

           •  Inside the run() method, it prints “Thread is running...” to indicate that the thread has started its execution.
           3.  main() Method:
           •  This method serves as the entry point of the program.
           •  Inside main():

           •  An instance of the IsAliveExample class named isAliveThread is created.
           •  The start() method is invoked on isAliveThread to begin the execution of the thread.
           •  Immediately after starting the thread, isAlive() method is called on isAliveThread to check if the thread is alive.
           •  The result of isAlive() method (which returns true if the thread is alive and false otherwise) is printed.



                                                           149
 CITS : IT & ITES - Computer Software Application - Exercise 104  CITS : IT & ITES - Computer Software Application - Exercise 104
   159   160   161   162   163   164   165   166   167   168   169