Inter thread communication in Java


Communication Java ThreadViews 3409

Inter thread communication in Java

Inter thread communication in Java or cooperation is the process of coordinating the communication between the synchronized threads. This means, when a new thread wants to enter the critical section, it pauses the currently executing thread to allow the new thread. In this way, if the synchronized threads cooperate with each other, it reduces the risk of a deadlock situation. We can implement inter-thread communication using the wait, notify, and notifyAll methods of the Object class.

Now, let’s see in detail each method below.

wait method

The wait() method pauses the current thread execution and waits until the time elapses or another thread invokes the notify() or notifyAll() method.

We can invoke the wait() method only within the synchronized method or synchronized block since the thread must own the monitor, else it will throw an exception. Once it calls the wait() method, it releases the current lock monitor.

public final void wait(long milliseconds) throws InterruptedException

What is a monitor

Whenever a synchronized thread wants to access a shared resource, it acquires a lock and enters the monitor. At a time, only one thread can own a monitor. The other threads need to wait until the first thread releases the monitor.

notify method

The notify method awakes the thread that called the wait method on the same resource. This causes the thread that was sleeping to resume its execution. If there were multiple threads in the wait state for the same shared resource, then it notifies any one of them.

public final void notify()

notifyAll method

The notifyAll method awakes all the threads that call the wait method on the same resource. If there are multiple threads, then it wakes up the highest priority thread.

public final void notifyAll()

Example of inter-thread communication in Java

Below is an example that helps you to understand how to implement inter-thread communication in java using wait, notify, and notifyAll methods.

class Stock {
  int qty = 15;
  
  synchronized void purchaseStock(int quantity) {
    System.out.println("Purchase stock");
    
    if(this.qty < quantity) {
      System.out.println("Insufficient quantity available");
      try {
        wait();
      }
      catch(Exception e) {
        e.printStackTrace();
      }
    }
    this.qty = this.qty - quantity;
    System.out.println("Purchase stock completed");
  }
  
  synchronized void addStock(int quantity) {
    System.out.println("Adding Product stock");
    
    this.qty = this.qty + quantity;
    System.out.println("Add stock completed");
    notify();
    
  }
}
public class InterThreadDemo {

  public static void main(String[] args) {
    Stock s = new Stock();
    new Thread() {
      public void run() {
        s.purchaseStock(20);
      }
    }.start();
    

    new Thread() {
      public void run() {
        s.addStock(10);
      }
    }.start();
  }

}
Purchase stock
Insufficient quantity available
Adding Product stock
Add stock completed
Purchase stock completed

Let us understand the above example in detail.

When the first thread calls the purchaseStock() method, it acquires the lock and checks if the required quantity is available in the stock. Since the requested quantity(which is 20) is lesser than the available quantity( which is 15), it calls the wait() method.

Now it releases the lock and starts the second thread since the first thread is in the wait state. The second thread calls the addStock() method which adds the required quantity to the available stock and then invokes the notify() method. The notify() method wakes up the first thread that had called the wait() method and resumes the execution.

Now, since the required stock is available, it decreases the requested quantity and updates the available stock, and completes the execution.

Inter thread communication in Java

Difference between wait and sleep

Though wait and sleep methods perform more or less the same operation, there are some differences as below.

waitsleep
Belongs to the Object classBelongs to the Thread class
It is a non-static methodIt is a static method
Wait operation is interrupted by notify or notifyAll methodsSleep operation is interrupted after a specified timeout
It releases lock when wait method is calledIt does not release or own any lock

Reference

Translate ยป