Can someone explain me the detail flow of wait(),notify() and notifyAll()...
Invocation of wait() causes the the current thread to wait until some other thread invokes notify()/notifyAll() for the same object which the wait() was invoked. You may want to look at concurrency tutorial to know more about concurrency here
Below you will see one example workflow for using Object.wait(), Object.notify(), and Object.notifyAll() for synchronizing multiple threads in Java.
There are many different reasons to synchronize between threads in Java, and so there are also multiple different paradigms for using the synchronized blocks, wait(), and notify() methods. What they all have in common would be the sharing of data and the need to signal some condition is met. You can take the wait() method as meaning 'I want to pause until the condition is met.' In this case, a notify() means 'The condition has been met. Let ONE wait()er know.' The notifyAll() then becomes 'The condition has been met. Let ALL wait()ers know.' In this situation, Object on which the wait(), notify(), or notifyAll() methods are called on represents the 'condition.' Since all the wait()ers and notify()ers want to work and notify on the same condition, they need access to the same Object. If they need to wait() or notify() on different conditions they would often use different Objects, or add an additional signal like a boolean flag.
It is not uncommon to require tasks to switch back and forth, one thread doing a portion of a task, and signaling to the other thread to continue. Then at some point needing to wait for the second thread to signal it is done. This this case you usually have each thread alternating between wait() and notify().
There are a few things that you have to be aware of:
1) If the notifier calls notify() before the waiter calls wait(), the waiter will not see it. This can sometimes lead to the waiter never getting a signal and blocking indefinitely. So there is often the need to send a boolean which says 'Signal was sent already, don't wait' as well as the notify().
2) There is also a chance of a 'spurious' wakeup which can cause the waiter to be notified even when the notifier has not yet sent its signal. This also is usually solved by using a boolean in addition to the normal notify().
The result is that you often will use a wait() something like this:
or some variation. Then the notifier does:
This would solve both of the notes above. Also note that I did not use that mechanism in my code below because it wasn't really necessary.
subject: Need Information about wait(),notiy(),notifyAll() in java