Java: How threads communicate with each other
Threads communicate with each other with the help of 3 Object class methods 1. wait() 2. notify() 3. notifyAll() Lets look at a simple example, Consider we have 2 threads, one is mail delivery thread and another is mail-processing thread. The mail-processing thread has to keep checking to see if there's any mail to process. The mail processing thread checks for any new mail for every 2 seconds. This is truly waste of time & cpu processing power. Instead of that using wait¬ify mechanism, when the mail-delivery thread puts a mail in mailbox & notifies mail-processing thread, so that it processes new mail. Key Points: 1. wait(), notify() & notifyAll() must be called from within a synchronized context. A thread cannot invoke a wait or notify method on an object unless it owns that object's lock. 2. If the thread calling wait() does not own the lock, it will throw an IllegalMonitorStateException. This exception is not a checked exception. But a wait...