Skip to content
Related Articles

Related Articles

Improve Article

wait() Method in Java With Examples

  • Last Updated : 06 Jun, 2021
Geek Week

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.

Syntax:

public final void wait() throws InterruptedException

Exceptions

Working:

  • 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.

Java




// Java program to demonstrate the use of wait() method
class GunFight {
    private int bullets = 40;
  
    // This method fires the number of bullets that are
    // passed it. When the bullet in magazine becomes zero,
    // it calls the wait() method and releases the lock.
    synchronized public void fire(int bulletsToBeFired)
    {
        for (int i = 1; i <= bulletsToBeFired; i++) {
            if (bullets == 0) {
                System.out.println(i - 1
                                   + " bullets fired and "
                                   + bullets + " remains");
                System.out.println(
                    "Invoking the wait() method");
                try {
                    wait();
                }
                catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(
                    "Continuing the fire after reloading");
            }
  
            bullets--;
        }
        System.out.println(
            "The firing process is complete");
    }
  
    // reload() increases the bullets by 40 everytime it is
    // invoked and calls the notify() method which wakes up
    // the thread that was sent to sleep using wait() inside
    // of fire() method
    synchronized public void reload()
    {
        System.out.println(
            "Reloading the magazine and resuming "
            + "the thread using notify()");
        bullets += 40;
        notify();
    }
}
  
public class WaitDemo extends Thread {
    public static void main(String[] args)
    {
  
        GunFight gf = new GunFight();
  
        // Creating a new thread and invoking
        // our fire() method on it
        new Thread() {
            @Override public void run() { gf.fire(60); }
        }.start();
  
        // Creating a new thread and invoking
        // our reload method on it
        new Thread() {
            @Override public void run() { gf.reload(); }
        }.start();
    }
}
Output
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

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.




My Personal Notes arrow_drop_up
Recommended Articles
Page :