I know that every object in Java has a lock, but what does “monitor lock” mean? Is it the same as locking an object?
Yes, it is one and the same. They are also sometimes called the mutex object and the primitive castle object. (But when someone talks about Lock
, they talk about this Java interface ... which is another locking mechanism.)
Why should the notification method refuse to lock the monitor?
The notify
method notify
not leave a lock. Your code is obliged to refuse blocking (i.e., leave the synchronized block or return from the synchronized method) after returning the notify
call.
Why is this necessary? Because any other thread that is currently waiting for this lock (in the wait(...)
call) must re-lock this lock before the wait
call completes.
Why did they design notify
/ wait
as follows? So that they can be used to implement variable conditions.
Like the first description above, does this mean that the current object is locked by a synchronized keyword, and then the wait method releases the lock?
It is right. When a thread calls someObject.wait()
, its lock on someObject
freed ... and then again (on the same thread) before wait()
returned. Of course, at the same time, someObject
could be acquired and released several times by other threads. The fact is that when wait
returns, the thread that called wait
will have a lock.
Stephen c
source share