Wait, Notify and NotifyAll

The multiple thread communication happening via each other by wait(), notify() and notifyAll() method in java. 

The object contain many in-build method, wait(), notify() and notifyAll() is one of them. So today we will discuss about these thee method. 



wait, notify and notifyAll in Java


wait(), notify() and notifyAll() should be call from synchronized context and should acquire lock on object monitor else it throws java.lang.IllegalMonitorStateException exception.


Lets see in details.



wait 


Syntax :

public final void wait() throws InterruptedException



When wait() method is called, the calling thread stops its execution until notify() or notifyAll() method is invoked by some other threads


notify


Syntax :

public final void notify();

When notify() method is called, It's wake up only one thread that's waiting for an Object and that thread will start the further execution. When multiple thread is waiting to wakeup and notify method is called only one thread will wake-up and other thread will still wait for more(until next notify get called). this method does not return any value.


notifyAll


Syntax :

public final void notify();

 An Alternative to notify() is notifyAll(). As the name implies this method wakes up all threads that are waiting for on the given object but awakened thread will not be able to proceed further until current thread not release the lock on same object


1 comment:

  1. Good explanation. Will implement accordingly in my personal projects.

    ReplyDelete