Thursday, February 26, 2026

Difference Between wait(), notify(), and notifyAll() in Java

These three methods are part of Java’s inter-thread communication mechanism. They help threads coordinate execution when working on shared resources.

All three methods belong to the Object class and must be used inside a synchronized context.






🔹 1. wait()

Purpose:
Makes the current thread release the lock and move into a waiting state until another thread notifies it.

Key Points

✔ Releases object monitor (lock)
✔ Thread goes to WAITING state
✔ Must be called inside synchronized block/method

Example

synchronized(obj) {
    obj.wait();   // thread pauses and releases lock
}

👉 Thread will resume only after notify() / notifyAll().


🔹 2. notify()

Purpose:
Wakes up one waiting thread randomly from the waiting pool.

Key Points

✔ Does NOT release lock immediately
✔ Awakened thread runs only after lock is released
✔ Useful when only one thread should continue

Example

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

🔹 3. notifyAll()

Purpose:
Wakes up all waiting threads on the same object.

Key Points

✔ All waiting threads become runnable
✔ Only one thread gets lock at a time
✔ Safer in complex thread coordination

Example

synchronized(obj) {
    obj.notifyAll();   // wakes all waiting threads
}

🔹 Comparison Table



🔹 Simple Real-Time Example (Producer–Consumer)

  • Consumer calls wait() when data is unavailable.

  • Producer adds data and calls notify().

  • If multiple consumers exist → use notifyAll().


🔹 Important Interview Points

wait() releases lock, sleep() does NOT
✅ Methods belong to Object, not Thread
✅ Always call inside synchronized block, otherwise → IllegalMonitorStateException


🚀 Practice Multithreading with Industry Scenarios

Learn threading, synchronization, JVM internals, and real production examples in Best Java Real Time Projects Online Training in ammerpet


No comments:

Post a Comment

To build frictionless production-ready Java applications in 2026, developers must move beyond traditional coding styles and adopt modern pra...