In this post, we will see "wait notify and notifyall example in Java | Multithreading synchronization in Java using wait, notify, notifyall"
wait(), notify(), notifyAll() methods are used in Java for multi-threading synchronization.
wait() method:
When any thread calls wait() method, it goes to waiting mode and allow other waiting threads to execute. Multiple threads can call wait() method and go to the waiting mode.
notify() method:
When any thread calls notify method, it frees the other thread who has called wait() first and allow it to execute in critical section.
notifyAll() method:
notifyAll() method frees all the threads who has called wait() method.
wait(), notify(), notifyAll() methods are used in Java for multi-threading synchronization.
wait() method:
When any thread calls wait() method, it goes to waiting mode and allow other waiting threads to execute. Multiple threads can call wait() method and go to the waiting mode.
notify() method:
When any thread calls notify method, it frees the other thread who has called wait() first and allow it to execute in critical section.
notifyAll() method:
notifyAll() method frees all the threads who has called wait() method.
Go through the following program. Here, we are creating two threads. One thread is withdrawing money while other thread is depositing money. If balance is less, then thread who is withdrawing money will call wait() method and goes to waiting mode. It allows other thread to deposit first. Once other thread deposits money, it calls notify() method which allows first thread to withdraw money.
Program (waitnotify.java)
class Customer { int amount=10000; synchronized void withdraw(int amount) { System.out.println("going to withdraw..."); if(this.amount<amount) { System.out.println("Less balance; waiting for deposit..."); try{wait();} catch(Exception e){} } this.amount=this.amount-amount; System.out.println("withdraw completed..."); } synchronized void deposit(int amount) { System.out.println("going to deposit..."); this.amount=this.amount+amount; System.out.println("deposit completed... "); notify(); } } class waitnotify { public static void main(String args[]) { Customer c=new Customer(); new Thread() { public void run() {c.withdraw(15000);} }.start(); new Thread() { public void run() {c.deposit(10000);} }.start(); } } |
Output:
parag@parag-Inspiron-N4010:~/Desktop/progbythread$ javac waitnotify.java
parag@parag-Inspiron-N4010:~/Desktop/progbythread$ java waitnotify going to withdraw... Less balance; waiting for deposit... going to deposit... deposit completed... withdraw completed... |
No comments:
Post a Comment