How to understand the wait and notify method in Java Thread? How to understand the wait and notify method in Java Thread? multithreading multithreading

How to understand the wait and notify method in Java Thread?


I know each object in Java has a lock, but what is the "monitor lock" means? is it the same as the object's lock?

Yes, they are the same thing. They are also occasionally called the object's "mutex" and the object's "primitive lock". (But when someone talks about Lock, they are talking about this Java interface ... which is a different locking mechanism.)

Why notify method needs to give up the monitor lock?

The notify method doesn't give up the lock. It is your code's responsibility to give up the lock (i.e. leave the synchronized block or return from the synchronized method) after the notify call returns.

Why is that necessary? Because any other thread that is currently waiting on that lock (in a wait(...) call) has to reacquire that lock before the wait call can complete.

Why did they design notify / wait like this? So that they can be used to implement condition variables.

Like the first description above, is that means the the current object is blocked by synchronized keyword, and then wait method releases the lock?

That is correct. When a thread calls someObject.wait() its lock on someObject is released ... and then reacquired (by the same thread) before the wait() call returns. Of course, in the meantime the lock someObject may have been acquired and released multiple times by other threads. The point is that when wait returns, the thread that called wait will have the lock.


  1. Yes, the monitor lock is the same as the object's lock. If you do synchronized (object), that's the lock.

  2. In your example, the current object will give up the lock while waiting, the wait() call gives up the lock. In another thread, notify() is called to wake the object up, and when the wait() call returns it will hold the lock again.


A monitor is a type of synchronization construct.

The reason that waiting gives up the lock is so that other threads can acquire the lock, such as other threads that might want to wait. Also: It's usual for the thread that's awakening other threads to lock before releasing any threads, to prevent a race condition.

For more about this, you should study condition variables (i.e. condvars).