Java Interthread communication


When two or more threads communicate with each other to exchange some information. This process is called Interthread communication.


The following three methods which make thread communication is possible.

  • wait()
  • notify()
  • notifyAll()

S.No Method Description
1 public void wait() It causes the current thread to wait until another thread calls the notify() or notifyAll().
2 public void notify() It wakes up a single thread that is waiting on this object's monitor.
3 public void notifyAll() It wakes up all the threads that called wait() on the same object.

All three methods can be called only from within a synchronized context.


Example:

class Customer {
    int Stock=1000;
    synchronized void get(int Stock) {
        if(this.Stock < Stock){
            System.out.println("Less Stock and Customer waiting for refill"); 
            try {
                wait();
            } catch(InterruptedException e) {
                System.out.println("InterruptedException caught");
            }
            this.Stock-=Stock;  
            System.out.println("Stock Soldout Sucessfully");  
        }
    }
    synchronized void put(int Stock) {
        System.out.println("Going for Stock refill");  
        this.Stock+=Stock;  
        System.out.println("Stock refill is completed ");  
        notify();
    }
}
class Producer implements Runnable {
    Customer cus;
    Producer(Customer cus) {
        this.cus = cus;
        new Thread(this, "Producer").start();
    }
    public void run() {
        cus.put(2000);
    }
}
class Consumer implements Runnable {
    Customer cus;
    Consumer(Customer cus) {
        this.cus = cus;
        new Thread(this, "Consumer").start();
    }
    public void run() {
        while(true) {
            cus.get(1500);
        }
    }
}
class Interruptingthread{
    public static void main(String args[]) {
        Customer cus = new Customer();
        new Consumer(cus);
        new Producer(cus);
    }
} 

What is the difference between wait and sleep?

S.No Sleep() method Wait() method
1 The Sleep method doesn't release the lock. The wait method releases the lock when we use notify or notifyAll.
2 The sleep is the method of Thread class The sleep is the method of Object class
3 It is static method It is non-static method
4 It is waiting for the specified amount of time. It should wake up by notifying () or notifyAll () methods.



OnlineTpoint is a website that is meant to offer basic knowledge, practice and learning materials. Though all the examples have been tested and verified, we cannot ensure the correctness or completeness of all the information on our website. All contents published on this website are subject to copyright and are owned by OnlineTpoint. By using this website, you agree that you have read and understood our Terms of Use, Cookie Policy and Privacy Policy.