First, two concepts: Lock pool and wait pool
- Lock pool: Assume that thread a already has a lock on an object (note: Not a Class), while other threads want to invoke some synchronized method (or synchronized block) of the object. Because these threads must obtain the ownership of the lock on the object before entering the object's synchronized method, the lock for that object is currently owned by thread A, so these threads enter the lock pool of the object.
- Wait pool: Assuming that a thread A calls the wait () method of an object, thread A will release the lock on the object and enter into the object's wait pool
lock pool and wait pool in Reference:java
Links: https://www.zhihu.com/question/37601861/answer/145545371
And then say the difference between notify and Notifyall.
- If the thread calls the object's Wait () method, the thread is in the object's wait pool , waiting for the thread in the pool to not compete for the lock on the object.
- When a thread calls the object's notifyall() method (waking all the wait threads) or the notify() method (which only randomly wakes up a wait thread), the awakened threads go into the object's lock pool. The thread in the lock pool will compete for that object lock. That is, when notify is called, as long as a thread is queued by the wait pool into the lock pool, Notifyall will wait for all threads in the pool to move to the lock pool, waiting for the lock to compete
- A high-priority thread competes for the probability of an object lock, and if a thread does not compete with the object lock, it will remain in the lock pool , and the Wait () method will be called again by the wired thread to return to the waiting pool. The thread that competes to the object lock continues execution until the synchronized code block is executed, releasing the object lock, and the thread in the lock pool continues to compete for that object lock.
Reference: Inter-thread Collaboration: Wait, notify, Notifyall
In summary, the so-called wake-up thread, another explanation is to move the thread from the waiting pool to the lock pool, after the Notifyall call, the entire thread will be moved by the wait pool to the lock pool, then participate in the competition of the lock, the competition continues to execute, and if unsuccessful, remain in the lock pool waiting for the lock to be released again The notify will only wake up a single thread.
With these theoretical foundations, the notify behind may lead to deadlocks, and the example of Notifyall would be a good explanation.
What is the difference between notify and Notifyall in Java?