Open In App

Difference Between wait() and notifyall() in Java

Last Updated : 23 Nov, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Multithreading is a Java feature that allows concurrent execution of two or more parts of a program for maximum utilization of CPU. Each part of such program is called a thread. So, threads are light-weight processes within a process. Multi-threaded programs may often come to a situation where multiple threads try to access the same resources and finally produce erroneous results.

So it needs to be made sure by some synchronization method that only one thread can access the resource at a given point of time.Java provides a way of creating threads and synchronizing their task by using synchronized blocks. Synchronized blocks in Java are marked with the synchronized keyword. A synchronized block in Java is synchronized on some object. All synchronized blocks synchronized on the same object can only have one thread executing inside them at a time.

We will be discussing the differences later let us do have a sneak peek how they are interrelated by discussing them individually as follows:

  1. wait() Method
  2. notifyAll() Method

1. wait() Method

In multithreading two threads can communicate Inter-thread communication with each other by using the wait() method. The thread which is expecting updation is responsible to call the wait() method and then immediately the thread will enter into the waiting state. The wait() method is present in java.lang.Object class not in Thread class because the thread can call this method on any java object. To call wait() method any java object the thread should be the owner of that object i.e, the thread should have lock of that object i.e, the thread should be inside the synchronized area. Hence, we can call the wait() method only from the synchronized area otherwise we will get RuntimeException saying  IllegalMonitorStateException. If a thread call wait() method on any object it immediately releases the lock of that particular object and enters in waiting state.

Syntax:

public  final void wait()

The above method cause the current thread to wait indefinitely until  either notify( ) or notifyAll( ) invokes  for this object.

public final native void wait( long microsecond)
public final void wait( long microsecond , int nanosecond)

Using the above two method we can specify a timeout after  which thread will be wake up automatically. We can wake up the thread before reaching the timeout using notify( ) or notifyAll( ) method.

Note: Do remember that every wait() method throws InterruptedException which is a checked exception hence whenever we are using the wait() method compulsory we should handle this  InterruptedException either by try-catch or by throws keyword otherwise we will get compile-time  error.

2. notifyAll() Method

Likewise of wait(), method notifyAll() method is used in inter-thread communication . The thread is responsible to perform updating  and after performing some updating it is responsible to call notifyAll() method then the waiting thread will get that notification and continue its execution with updated items. notifyAll() is also present in java.lang .Object class. To call notifyAll() method on any object they should be the owner of that object i.e, the thread should be inside synchronized area. Hence, we can call notifyAll() method only from the synchronized area otherwise we will get RuntimeException saying IllegalMonitorStateExceptiom. One can use notifyAll() method to give the notification to all waiting threads of a particular object but even though multiple threads gets notify but the execution will be performing one by one because the thread required to lock and only one lock is available at a moment.

Syntax:

public final native void notifyAll()

Implementation: 

In the below example we create a class ‘myThread’, generally it is named this way in program which extends our Thread class which in itself extends the java.lang .Thread class. This class overrides the run() method available in the Thread class a thread begins its life cycle inside the run() method. In the driver class ThreadN we create an object and call the start method to start the execution of a thread and invokes the run() method in ThreadN class we synchronized the t1 thread and put it into waiting state. Inside the myThread class, we synchronize the run method and after calculating the sum we use notifyAll() method to give notification to the waiting thread.

Example

Java




// Java Program to illustrate difference between
// wait() and notifyAll() method
 
// Importing java classes
// Input output classes
import java.io.*;
import java.lang.*;
// All utility classes from
// java.util package
import java.util.*;
 
// Creating a thread in our myThread class
// by extending the Thread class
 
// Class 1
// Helper class
class myThread extends Thread {
 
    // Declaring sum variable and
    // initializing with zero
    // as the current final sum
    // as it is before iteration
    int sum = 0;
 
    // Method in helper class
    // Declaring run method
    public void run()
    {
 
        // Synchronizing this method
        synchronized (this)
        {
            // Calculating the sum
 
            // Display message
            System.out.println(
                "child thread start calculation");
 
            // Iterating to calculate the sum
            for (int i = 0; i <= 100; i++)
 
                // Updating the current sum where
                // last updated sum is final sum
                sum += i;
 
            // Display message
            System.out.println(
                "child thread trying to give notification");
 
            // This keyword refers to current object itself
 
            // Notifying the current waiting thread
            // using notifyAll() method
            this.notifyAll();
        }
    }
}
 
// Class 2
// Main class
class ThreadN {
 
    // Main driver method
    public static void main(String[] args)
        throws InterruptedException
    {
 
        // Creating a thread object
        // in the main() method of
        // our helper class above
        myThread t1 = new myThread();
 
        // Starting the above thread created
        // using the start() method
        t1.start();
 
        // Synchronizing the thread
        synchronized (t1)
        {
            // Display message
            System.out.println(
                "main thread trying to call wait method");
 
            // Putting the thread in the waiting state
            // using the wait() method
            t1.wait();
 
            // Display message
            System.out.println("main thread get notify");
 
            // Print and display the sum
            System.out.println(t1.sum);
        }
    }
}


 
 

Output

main thread trying to call wait method
child thread start calculation
child thread trying to give notification
main thread get notify
5050

Now if the same program is run on terminal/CMD for custom user defined input then the hard coded input is shown below

Conclusion from the above program verifies the key differences between wait() and notifyAll() methods as follows: 

  1. wait() is used to put the thread in waiting state while the notifyAll() method wake up all the waiting thread of a particular object.
  2. If a thread calls wait() method on any object it immediately releases the lock of that particular object but if a thread calls notifyAll() method on any object it also releases the lock of that particular object but not immediately.
  3. wait() method throws an InterruptedException while notifyAll() method doesn’t throw any InterruptedException.

 Let us see the differences in a tabular form -:

  wait() notifyall()
1. The wait() method is defined in Object class The notifyAll() method of thread class is used to wake up all threads.
2. It tells the calling thread (Current thread) to give up the lock and go to sleep until some other thread enters the same monitor and calls notify() or notifyAll() It gives the notification to all waiting threads of a particular object.
3. It can not be overridden It does not have any return type.
4. It is used for interthread communication It is implemented in Object class as final methods
5. It is tightly integrated with the synchronization lock It must be called within a synchronized method or block


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads