Wait, Notify and NotifyAll methods Thread in Java

The wait() method is used to suspend the execution of a thread until a certain condition is met. The wait() method is defined in the Object class and can be called on any object. When a thread calls the wait() method on an object, it releases any locks it holds on the object and goes to sleep until one of the following events occurs:

* Another thread calls the notify() or notifyAll() method on the same object.

* A specified amount of time has elapsed.

Here's an example to illustrate how to use the wait() method:

                
    class MyThread implements Runnable {
        private Object lock;

        public MyThread(Object lock) {
            this.lock = lock;
        }

        public void run() {
            synchronized(lock) {
                try {
                    System.out.println(Thread.currentThread().getName() + " is waiting...");
                    lock.wait();
                    System.out.println(Thread.currentThread().getName() + " is awake!");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public class WaitExample {
        public static void main(String[] args) {
            Object lock = new Object();

            Thread thread1 = new Thread(new MyThread(lock));
            Thread thread2 = new Thread(new MyThread(lock));

            thread1.start();
            thread2.start();

            try {
                Thread.sleep(1000); // Sleep for 1 second to ensure threads start
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            synchronized(lock) {
                lock.notifyAll();
            }
        }
    }
                
            

In this example, we have a MyThread class that implements the Runnable interface. The constructor of MyThread takes an Object as an argument, which will be the lock that the thread will use to synchronize access to shared resources.

In the run() method of MyThread, we first synchronize on the lock object and then call wait() on it. This causes the thread to release the lock and go to sleep until another thread calls notify() or notifyAll() on the same object.

In the main() method, we create two threads and start them. We then sleep for 1 second to ensure that the threads have started and are waiting. Finally, we synchronize on the lock object and call notifyAll() to wake up all waiting threads.

When notifyAll() is called, both threads will wake up and continue executing. The output of the program will be something like:

                
    Thread-0 is waiting...
    Thread-1 is waiting...
    Thread-1 is awake!
    Thread-0 is awake!
                
            

Note that the order in which the threads wake up is not guaranteed. It could be either Thread-0 or Thread-1 that wakes up first.