- Two Threads can communicate with each other by using wait(), notify() and notifyAll() methods.
- The Thread which is excepting updation is responsible to call wait() method on the required object then immediately the Thread will entered into waiting state.
- The Thread which is responsible to perform updation, after performing updation, it is responsible to call notify() method then waiting Thread will get that notification and continue its execution with those updated items.
- wait(), notify(), notifyAll() methods present in Object class but not in Thread class because Thread can call these methods on any java object.
- To call wait(), notify(), notifyAll() methods on any object , Thread should be owner of that object
- i.e. the Thread should has lock of that object.
- i.e the Thread should be in Synchronized area.
- Hence we can call wait(), notify(), notifyAll() methods only from Synchronized area otherwise we will get runtime exception saying IllegalMonitorStateException.
- If a Thread calls wait() method on any object it immediately releases the lock of that particular object and entered into waiting state.
- If a Thread call notify() on any object, it releases the lock of the object may not immediately.
- Except wait(), notify() and notifyAll() there is no other method where Thread releases the lock.
Method
|
Is Thread
Releases Lock?
|
yield()
|
No
|
join()
|
No
|
sleep()
|
No
|
wait()
|
Yes
|
notify()
|
Yes
|
notifyAll()
|
Yes
|
Producer consumer problem
- Producer Thread is responsible to produce items to the queue and consumer Thread is responsible to consume items from the queue.
- If queue is empty then consumer Thread will call wait() and enter into the waiting state.
- After producing items to the queue producer Thread is responsible to call notify() than waiting consumer will get that notification and continue its execution with updated items.
Diagram:
Example:
Notify vs notifyAll():
- We can use notify() method to give notification for only one Thread. If multiple Threads are waiting then only one Thread will get the chance and remaining Threads has to wait for further notification. But which Thread will be notify(inform) we can't expect exactly it depends on JVM.
- We can use notifyAll() method to give the notification for all waiting Threads. All waiting Threads will be notified and will be executed one by one, because they are required lock.
Thanks..!!
No comments:
Post a Comment