Wait and notify methods are synchronized
In Java, the wait() and notify() methods are called from within synchronized blocks or methods because they are used for inter-thread communication and coordination, and they operate on the monitor associated with an object. Here’s why they are called from synchronized blocks:

Table of Contents
1. Ensuring Mutual Exclusion
Synchronized blocks or methods ensure that only one thread can execute a synchronized block of code or method at a time. This prevents concurrent modification of shared data and avoids race conditions.
2. Releasing and Acquiring Locks
When a thread invokes the wait() method, it releases the lock it holds on the object’s monitor, allowing other threads to enter synchronized blocks or methods on the same object. Similarly, when a thread invokes the notify() method, it notifies other threads waiting on the same object’s monitor to wake up and compete for the lock.
By calling wait() and notify() from within synchronized blocks, we ensure that the thread invoking these methods holds the lock on the object’s monitor, preventing inconsistencies or conflicts due to multiple threads accessing shared resources simultaneously.
Let’s illustrate the usage of wait() and notify() methods within synchronized blocks in Java:
java
public class WaitNotifyExample {
private boolean condition = false;
public synchronized void waitForCondition() {
while (!condition) {
try {
wait(); // wait until condition becomes true
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("Condition is now true, proceeding...");
}
public synchronized void setConditionTrue() {
condition = true;
notify(); // notify a single waiting thread
}
public static void main(String[] args) {
WaitNotifyExample example = new WaitNotifyExample();
Thread thread1 = new Thread(() -> {
example.waitForCondition();
});
Thread thread2 = new Thread(() -> {
example.setConditionTrue();
});
thread1.start();
thread2.start();
}
}
In this example, Wait and notify
Example with synchronized methods waitForCondition() and setConditionTrue(). The waitForCondition() method waits until the condition becomes true using the wait() method within a synchronized block. The setConditionTrue() method sets the condition to true and notifies the waiting thread using the notify() method, also within a synchronized block. This ensures that the calling thread holds the lock on the object’s monitor while invoking wait() and notify(), preventing concurrent access issues.