Inter Thread Communication:
Another advantage of the thread: It avoids polling. (i.e., One thread polling and thus wasting more CPU cycles waiting for the other threads to finish etc)
This is done by wait(), notify() and notifyAll() methods of Object class and so all classes have them.
- final void wait() throws InterruptedException
-tells the calling thread to give up the monitor and go to sleep until some other thread enters the monitor and calls notify()
- final void notify()
-wakes up a thread that called wait() on the same object
- final void notifyAll()
-wakes up all the threads that called wait() on the same object. One of the threads will be granted access.
Note: These methods can be called only from within a synchronized context.
Oracle recommends that calls to wait() should take place within a loop that checks the condition on which the thread is waiting.
Producer-Consumer Problem: The Consumer should consume only if the Producer produces and Producer should continue producing only if the consumer has consumed the already produced data.