This article mainly introduces the relevant information about the comparison between java notify and notifyAll. Friends in need can refer to
java notify and notifyAll
First of all, you can understand from the name that notify notifies a thread to acquire a lock, and notifyAll notifies all related threads to compete for the lock.
notify cannot guarantee that the thread that obtained the lock actually needs the lock, and may cause deadlock.
Example 1:
Everyone (consumer thread) is ready to eat, the canteen is not open (the lock is not released), the meal window (lock), everyone is waiting ( WAITING).
The canteen opens the meal window (releases the lock), and broadcasts the message "dinner is served" (notifyAll). Everyone competes to line up and wait to eat (BLOCKED). Each person plays (RUNNABLE) in the cooking window (obtains the lock) in turn. If you want to eat, just finish the meal and leave (release the lock). If you don’t want to eat, just leave directly (release the lock). If you still want to eat after eating, take the initiative to wait for the next "dinner is ready" message (wait).
The canteen notifies a person to come to eat (notify), and this person comes to the meal window (obtains the lock) to make meal (RUNNABLE), and everyone else is waiting for the news of meal opening (WAITING). If you want to eat, just finish the meal and leave (release the lock). If you don’t want to eat, just leave directly (release the lock). If you still want to eat after eating, take the initiative to wait for the next "dinner" message (WAITING).
notify cannot guarantee that people who really want to eat will be notified.
Example 2:
Two producers P1 and P2, and two consumers C1 and C2, jointly operate a queue with a maximum queue length of 1.
Start with P1, P2, C1, and C2 all in running status (RUNNABLE).
C1 obtains the lock first, and P1, P2, and C2 are in the BLOCKED state. C1 finds that the queue is empty and actively enters WAITING. C2 then obtains the lock, becomes RUNNABLE state, finds that the queue is empty, and actively enters WAITING.
P1 then acquires the lock, becomes the RUNNABLE state, inserts an element into the queue, and notifies another producer P2. P1 produces in a loop and finds that the queue is not empty and becomes WAITING.
P2 becomes RUNNABLE state, finds that the queue has value, and actively enters WAITING.
The lock has been released at this time, but P1, P2, C1, and C2 are all in the WAITING state. There is no thread to acquire the lock and they are dead.
Related articles:
Two ways to collaborate between threads in java concurrency: wait, notify, notifyAll and Condition
wait, The correct usage of notify and notifyAll
Discuss the essential difference between notify() and notifyAll() through examples
The above is the detailed content of A detailed introduction to the comparison between java notify and notifyAll. For more information, please follow other related articles on the PHP Chinese website!