Sobes.tech
Junior — Middle

What is the purpose of using the wait() method in the Object class in Java?

sobes.tech AI

Answer from AI

The wait() method is used to suspend the execution of the current thread until another thread calls notify() or notifyAll() on the same object. This is a key mechanism for coordinating interactions between threads in Java, allowing one thread to wait for a specific condition while releasing the object's monitor.

Example:

synchronized(obj) {
    while (!condition) {
        obj.wait(); // the thread waits until condition becomes true
    }
    // continue work
}

Here, the thread waits until the condition is met, without blocking the CPU, allowing other threads to change the state and call notify().