wait() Method in Java With Examples
Inter-Thread communication is a way by which synchronized threads can communicate with each other using the methods namely wait(), notify() and notifyAll(). wait() method is a part of java.lang.Object class. When wait() method is called, the calling thread stops its execution until notify() or notifyAll() method is invoked by some other Thread.
public final void wait() throws InterruptedException
- InterruptedException – if any thread interrupted the current thread before or while the current thread was waiting for a notification.
- IllegalMonitorStateException – if the current thread is not the owner of the object’s monitor.
- In java, synchronized methods and blocks allow only one thread to acquire the lock on a resource at a time. So, when wait() method is called by a thread, then it gives up the lock on that resource and goes to sleep until some other thread enters the same monitor and invokes the notify() or notifyAll() method.
- Calling notify() wakes only one thread and calling notifyAll() wakes up all the threads on the same object. Calling both these methods does not give up the lock on the resource, rather its job is to wake up the threads that have been sent to the sleep state using wait() method.
- A big difference between sleep() method and wait() method is that sleep() method causes a thread to sleep for a specified amount of time while wait() causes the thread to sleep until notify() and notifyAll() are invoked.
In the code mentioned below, we have created a class GunFight which contains a member variable bullets that is initialized to 40 and two methods fire() and reload(). The fire() method fires the number of bullets passed to it until the bullets become 0 and when bullets become 0 it invokes the wait() method which caused the calling thread to sleep and release the lock on the object while reload() method increased the bullets by 40 and invokes the notify() method which wakes up the waiting thread.
40 bullets fired and 0 remains Invoking the wait() method Reloading the magazine and resuming the thread using notify() Continuing the fire after reloading The firing process is complete