In Java, the wait() and notify() methods are used for inter-thread communication and synchronization. They are typically called from within synchronized blocks or methods to coordinate the execution of threads and ensure safe access to shared resources. Here's why wait() and notify() are used from synchronized methods:
Synchronization Requirement:
The wait() and notify() methods are designed to work in conjunction with the intrinsic lock (monitor) of an object. They require the thread invoking them to hold the lock of the object on which they are called. In Java, synchronized blocks and methods provide a convenient way to acquire and release locks.
Preventing Concurrent Access:
When a synchronized method is executed, the thread holds the lock of the object associated with the instance of the class containing the method. This prevents other threads from concurrently accessing synchronized methods or blocks on the same object.
Safe Use of wait() and notify():
To use wait() and notify() safely, the thread must hold the lock of the object on which these methods are called. This ensures that the thread invoking notify() can wake up the correct waiting thread and that the waiting thread will not proceed until the appropriate synchronization conditions are met.
Thread Coordination:
Threads often need to coordinate their execution based on specific conditions. For example, a thread might wait until a certain resource becomes available or until a condition is met. The wait() and notify() methods allow threads to pause their execution and wait for conditions to change, while notifying other threads when conditions are met.
By using wait() and notify() within synchronized methods, you ensure that the necessary synchronization mechanisms are in place to manage the state changes and interactions between threads.