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. |
Quickly Find What You Are Looking For
Onlinetpoint is optimized for basic learning, practice and more. Examples are well checked and working examples available on this website but we can't give assurity for 100% correctness of all the content. This site under copyright content belongs to Onlinetpoint. You agree to have read and accepted our terms of use, cookie and privacy policy.