简体   繁体   中英

In Java, why does a thread have to compete for resources after waking up from .wait()?

For example in this classic consumer-producer code snippet:

synchronized (this) {
  while (queue.isEmpty()) {
    this.wait();
  }
  queue.remove();
  this.notifyAll();
}

The .wait() consumer thread that is notified by producer will wake up and then compete for resource with other consumer threads that are waiting on synchronized (this) . This causes the race condition. But why don't simply let the .wait() consumer to hold the resource until it exists the synchronized block?

This is a naive question.. Thanks to the comments I think I understand the logic behind of the design now:

  1. The .wait() thread cannot just hold the lock when waiting, because that way producers are not able to write into the queue.
  2. When .wait() thread wakes up, why can't just guarantee it to get the lock? Because due to reason #1, .wait() thread has to give up the resource before start waiting. At the meantime, other consumer threads could reach the .wait() stage. Since there are many thread waiting, who should get the resource? Java chose to treats all threads the same let alone the time in wait.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM