Middle
What does the wait method do in Java?
sobes.tech AI
Answer from AI
The current thread is put into a waiting state (releasing the object's lock) until another thread calls the notify() or notifyAll() method on the same object, or until a timeout occurs. It is used in synchronized blocks or methods.
// Example of using wait() and notify()
public class SharedObject {
private boolean dataAvailable = false;
public synchronized void waitForData() throws InterruptedException {
while (!dataAvailable) {
// Thread waits until data becomes available
wait();
}
// Data processing
System.out.println("Data received.");
}
public synchronized void sendData() {
// Sending data
dataAvailable = true;
// Notify waiting threads
notifyAll();
System.out.println("Data sent.");
}
}
Key points:
- Called only from a synchronized context (block or method).
- The thread releases the lock on the object for which
wait()was called. - Can be interrupted (
InterruptedException). - Has overloaded versions with timeout.
notify()wakes up one of the waiting threads.notifyAll()wakes up all waiting threads.