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

COMPUTER SOFTWARE APPLICATION - CITS




           2  join() Method:
           •  Purpose: Waits for the thread on which it’s called to die.
           •  Syntax:join()
           •  Use Case:
           •  Ensures that the current thread waits for the completion of the thread on which join() is called before proceeding.
              class JoinExample extends Thread {
                public void run() {
                System.out.println(“Thread is running...”);
                }
                public static void main(String args[]) throws InterruptedException {
                JoinExample joinThread = new JoinExample();
                joinThread.start();
                joinThread.join();
                System.out.println(“Thread has finished”);
               }
           }
           Explanation:
           1  JoinExample 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 JoinExample class named joinThread is created.
              •  The start() method is invoked on joinThread to begin the execution of the thread.
              •  The join() method is called on joinThread. This causes the main thread to wait until joinThread finishes its
                 execution before continuing further.
              •  After joinThread finishes executing, “Thread has finished” is printed to indicate that the join operation has
                 completed.
           4  Output:
              •  When the program is executed:
              •  The thread starts its execution and prints “Thread is running...”.
              •  Meanwhile, the main thread waits for joinThread to finish its execution using the join() method.
              •  Once joinThread finishes executing, “Thread has finished” is printed by the main thread.
           5  Exception Handling:
           •  The join() method can throw an InterruptedException if the thread is interrupted while waiting for another
              thread to finish.
           •  In this example, the main() method declares that it throws InterruptedException. However, no explicit handling
              of the exception is performed within the method.





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