Page 369 - CITS - Computer Software Application -TT
P. 369

COMPUTER SOFTWARE APPLICATION - CITS




           LESSON 101 - 108 : Multithreading and Exception Handling
                                            in  Java






           In Java programming, threads enable concurrent execution and multitasking within an application. Understanding
           the life cycle of threads in Java and the various states is essential for efficient and synchronized thread management.

           Importance of understanding the life cycle of Thread in Java and its states

           The thread life cycle in Java is an important concept in multithreaded applications. Let’s see the importance of
           understanding life cycle of thread in java:

           1  Understanding the life cycle of a thread in Java and the states of a thread is essential because it helps
               identify potential issues that can arise when creating or manipulating threads.

           2  It allows developers to utilize resources more effectively and prevent errors related to multiple threads
               accessing shared data simultaneously.
           3  Knowing the thread states in Java helps predict a program’s behaviour and debug any issues that may arise.

           4  It also guides the developer on properly suspending, resuming, and stopping a thread as required for a
               specific task.

           The Life Cycle of Thread in Java - Threads State

           In Java, the life cycle of Thread goes through various states. These states represent different stages of execution.
           Here are examples of each stage of the life cycle of Thread in Java with real-life use cases:

           •   New (born) state

             -  Example: Creating a new thread using the Thread class constructor.

             -  Use case: Creating a new thread to perform a background task while the main Thread continues with other
                operations

           •  Runnable state

             -  Example: After calling the start() method on a thread, it enters the runnable state.

             -  Use case: Multiple threads competing for CPU time to perform their tasks concurrently.

           •  Running state

             -  Example: When a thread executes its code inside the run() method.

             -  Use case: A thread executing a complex computation or performing a time-consuming task.

           •  Blocked state

             -  Example: When a thread tries to access a synchronized block or method, but another thread already holds
                the lock.

             -  Use case: Multiple threads accessing a shared resource can only be obtained by a single Thread, such as
                a database or a file.





                                                           356
   364   365   366   367   368   369   370   371   372   373   374