Wait and notify

  • Eclipse: Oxygen
  • Java: 1.8

The basic concept of wait and notify is explained in this tutorial. It tells the calling thread to get rid of lock and go to sleep until some other threads enter the same monitor and calls notify() method. The wait() method releases the previous lock and reacquires the lock prior to returning from the wait() method.

This is a complete example of calling wait and notify method in Java using two threads.

We have shared two threads called thread1 and thread2. Inside thread1 we are simply calling the withdraw method and inside thread2 the deposited method.

Inside the withdraw method the condition is that if the balance amount is (balance <= 0), we won’t be able to withdraw amount and we have displayed a message “Waiting for balance updation”.

So thread1 will start waiting where we call the withdraw method until the thread2 calls the notify method.

Inside the deposit method, we are displaying “We are depositing the amount” and update the balance.

This inter-thread communication is achieved using wait() and notify() method. Remember wait() and notify() method is defined in the object class, and they must be called inside the synchronized block.
When notify() method is called the lock on the wait method would be released. We would be able to perform the operation.


Waiting for balance updation

We are depositing the amount

Withdrawal successful and the current balance is: 1000

Contributed by: Poonam Tomar

Full stack Java Developer

   Buy me a coffee!



Download file

Leave a Reply

Notify of
Close Menu