In Java, the wait() method is used for inter-thread communication, allowing threads to coordinate execution. It pauses a thread and releases the lock so that other threads can perform tasks. The thread resumes only when notified using notify() or notifyAll().
- The current thread releases the lock on the object
- The thread enters a waiting (sleep) state
- Another thread can acquire the lock and perform operations
- notify() wakes one waiting thread
- notifyAll() wakes all waiting threads
- After notification, the thread resumes execution
Example: GunFight has 40 bullets; fire() uses wait() when empty, and reload() refills bullets and calls notify() to resume the thread.
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
Syntax:
public final void wait() throws InterruptedException
Exceptions
- 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.