Wait, notify, and notifyAll
The wait(), notify(), and notifyAll() methods are not directly inside the Thread class in Java because they are used for inter-thread communication and coordination, rather than for controlling the behavior of individual threads. These methods are actually defined in the Object class, which is the superclass of all Java objects.
Table of Contents
Here’s why they are placed in the Object class:
1. wait(): This method causes the current thread to w until another thread invokes the notify() method or the notifyAll() method for this object. It’s used for threads to for a specific condition to be met before proceeding.
2. notify(): This method wakes up a single thread that is on this object’s monitor. If multiple threads are , it’s not specified which one will be awakened.
3. notifyAll(): This method wakes up all threads that are on this object’s monitor. It gives all threads a chance to check the condition and resume execution if the condition they were for has been satisfied.
Since these methods are closely tied to the concept of locking and on objects, it makes sense to define them in the Object class, as they can be used with any Java object to enable communication and synchronization between threads.
Let’s illustrate the usage of w(), notify(), and notifyAll() methods in Java:
java
public class WaitNotifyExample {
private boolean condition = false;
public synchronized void ForCondition() throws InterruptedException {
while (!condition) {
wait(); // w until condition becomes true
}
System.out.println("Condition is now true, proceeding...");
}
public synchronized void setConditionTrue() {
condition = true;
notifyAll(); // notify all threads on this object
}
public static void main(String[] args) {
WaitNotifyExample example = new WaitNotifyExample();
Thread thread1 = new Thread(() -> {
try {
example.waitForCondition();
} catch (InterruptedException e) {
e.printStackTrace();
}
});
Thread thread2 = new Thread(() -> {
example.setConditionTrue();
});
thread1.start();
thread2.start();
}
}
In this example, we have a class Example with a boolean condition. The ForCondition() method is called by a thread to w until condition becomes true. Inside this method, we use to make the thread until condition changes. The setConditionTrue() method is called by another thread to set condition to true and notify all threads using notifyAll(). This wakes up all threads that are on this object’s monitor.