java notify versus notifyAll

  • 2020-06-03 06:40:09
  • OfStack

java notify and notifyAll

First of all, notify tells one thread to get the lock, and notifyAll tells all relevant threads to compete for the lock.

notify does not guarantee that the thread acquiring the lock, that the lock is really needed, and that deadlocks can occur.

Example 1:

Everyone (consumer thread) is ready to eat, the canteen is not open (no release lock) hit the meal window (lock), everyone is waiting (WAITING).

The canteen opens the meal to hit the meal window (release the lock), and broadcasts the message "meal is served" (notifyAll), everyone competes to queue up and wait to eat (BLOCKED). Each person in turn in the rice window (get lock) rice (RUNNABLE). If you want to eat, leave after the meal (release the lock), do not want to eat directly leave (release the lock). If you still want to eat, take the initiative to wait for the next "meal" message (wait).

The canteen informs one person to come for dinner (notify), who comes to the threshing window (lock obtained) threshing (RUNNABLE), while others are waiting for the message of meal opening (WAITING). If you want to eat, leave after the meal (release the lock), do not want to eat directly leave (release the lock). If you still want to eat, take the initiative to wait for the next "meal" message (WAITING).
notify is not guaranteed to inform people who actually want to eat.

Example 2:

Two producers, P1 and P2, and two consumers, C1 and C2, jointly operate a queue with a maximum length of 1.

P1, P2, C1, C2 are all running at the start (RUNNABLE).

C1 obtains the lock first, and P1, P2 and C2 are BLOCKED states. C1 finds the queue empty and actively enters WAITING. C2 then acquires the lock, becomes the RUNNABLE state, finds the queue empty, and actively enters WAITING.

P1 then acquires the lock, becomes the RUNNABLE state, inserts one element into the queue, and notify goes to another producer P2. P1 loops production and finds that the queue is not empty, becoming WAITING.

P2 becomes RUNNABLE status, finds queue has value, enters WAITING actively.

At this point, the lock has been released, but P1, P2, C1, C2 are all in WAITING state, there is no thread to get the lock, and they are dead.

Thank you for reading, I hope to help you, thank you for your support to this site!


Related articles: