I just have a question in regards to threads that run concurrently and the lock they have on an object. From what I understand is that the thread that calls the wait() method will go on a waiting list and allows another thread from a blocked list to take over the lock on and object(within synchronized code).
If this thread that now has the lock on the object calls the notify() method it wakes up the thread that called wait() and it is moved to the blocked list.
What happens to the thread that calls the notify() method. Does it still have a lock on the object or does it now go on a waiting list?
regards
Only one thread can hold the lock for an object. The
wait()andnotify()methods must be called while the thread holds the lock on the object you call these methods on; if they don’t (for example, because you didn’t synchronize on the object), you’ll get anIllegalMonitorStateException.When you call
wait(), then the thread gives up the lock and goes on a waiting list (stops executing). Whenwait()returns, the thread will have obtained the lock again. However, the thread that callsnotify()is still holding the lock, so the waiting thread will not resume before the notifying thread exits thesynchronizedblock or method so that it releases the lock on the object.By calling
notify()the thread is not giving up the lock on the object.A possible sequence of events would be:
synchronizedblock, obtaining the lock for the objectwait()on the object, giving up the lock, stops executingsynchronizedblock, obtaining the lock for the objectnotify()on the object, but still holds the locksynchronizedblock and releases the lockwait()