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

COMPUTER SOFTWARE APPLICATION - CITS




           Explanation:
           1  SetNameExample 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 SetNameExample class named setNameThread is created.
              •  The setName() method is invoked on setNameThread to set the name of the thread to “CustomThreadName”.
              •  The start() method is invoked on setNameThread to begin the execution of the thread.
              •  Immediately after starting the thread, getName() method is called on setNameThread to retrieve the name
                 of the thread.
              •  The name of the thread is then printed.
           4  Output:
              •  When the program is executed:

              •  The thread starts its execution and prints “Thread is running...”.
              •  Meanwhile, in the main thread, the name of the thread (CustomThreadName)  is retrieved using  the
                 getName() method and printed.

               •  No explicit exception handling is performed in this program.
           This program demonstrates how to set and get the name of a thread in Java using the setName() and getName()
           methods. Naming threads can be helpful for identification and debugging purposes in multithreaded applications.
           Output:




































                                                           151
 CITS : IT & ITES - Computer Software Application - Exercise 104  CITS : IT & ITES - Computer Software Application - Exercise 104
   161   162   163   164   165   166   167   168   169   170   171