Sobes.tech
Junior — Middle

What is the purpose of the notify method in the Object class in Java?

sobes.tech AI

Answer from AI

The notify() method in the Object class in Java is used to wake up one of the threads that are waiting on the monitor of this object (i.e., have called wait() on this object).

When a thread calls notify(), it signals that the state of the object has changed, and one of the waiting threads can continue execution. If there are multiple threads, one of them is chosen arbitrarily to be awakened.

Important:

  • notify() should be called within a synchronized block or method synchronized on this object.
  • To wake all waiting threads, the notifyAll() method is used.

Example:

synchronized(obj) {
    obj.notify(); // wakes up one thread waiting on obj
}

Thus, notify() serves to coordinate thread work through the wait and notify mechanism.