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

COMPUTER SOFTWARE APPLICATION - CITS




            •  Waiting state
              -  Example: Using the wait method inside a synchronized block, a thread can wait until another thread calls
                 the notify() or notifyAll() methods to wake it up.

              -  Use case: Implementing the producer-consumer pattern, where a thread waits for a specific condition to
                 be met before continuing its execution
            •  Timed waiting state
              -  Example: Using methods like sleep(milliseconds) or join(milliseconds) causes a thread to enter the timed
                 waiting state for the specified duration.
              -  Use case: Adding delays between consecutive actions or waiting for the completion of other threads
                 before proceeding.
            •  Terminated state
              -  Example: When the run() method finishes its execution or when the stop() method is called on the Thread.
              -  Use case: Completing a task or explicitly stopping a thread’s execution.

            Example: Thread Life Cycle in Java:
            Here’s an example that demonstrates the life cycle of Thread in Java:
            public class ThreadLifecycleExample {
                public static void main(String[] args) {
                    Thread thread = new Thread(() -> {
                        System.out.println(“Thread is running.”);

                        try {
                            Thread.sleep(2000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();

                        }
                        System.out.println(“Thread is terminating.”);
                    });
                    System.out.println(“Thread is in the New state.”);
                    thread.start();

                    System.out.println(“Thread is in the Runnable state.”);
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {

                        e.printStackTrace();
                    }
                    System.out.println(“Thread is in the Timed Waiting state.”);
                    try {
                        thread.join();
                    } catch (InterruptedException e) {

                        e.printStackTrace();
                    }
                    System.out.println(“Thread is in the Terminated”);


                                                           357

                             CITS : IT&ITES - Computer Software Application - Lesson 101 - 108
   365   366   367   368   369   370   371   372   373   374   375