I read in a Java textbook the following pertaining to multi-threading.
For a thread to call wait() or notify(), the thread has to be the owner of the lock for that object. When the thread waits, it temporarily releases the lock for other threads to use, but it will need it again to continue execution.
I'm confused about what is meant by the clause
When the thread waits, it temporarily releases the lock for other threads to use
I don't get what that clause is talking about. Is it saying that when the wait() method is called it is actually releasing the lock before the wait() returns (i.e. this happens without caller knowing)? Or is it just alluding to wait(timeout) releasing the lock when the timeout elapses? If it is the former why would it release the lock before notify()? This seems like a vague and poorly explained statement.
wait(), the thread owns the lock, after callingwait(), the thread give up the lock, and wait for notify, on returning fromwait(), it owns the lock again. Always callwait()with in awhile()loop, it helps to check condition both before & after get the lock. JUST write a demo usingwait()andnotify()/notifyAll()to see how it works, you can't understand it without impl it by yourself.wait()(or its timeout overloads) must release the lock otherwise how could anotherThreadobtain the lock in order callnotify()/notifyAll()? Also, note that aThreadobtains a lock of anObjectby usingsynchronized (someObj) {...}.