gpt4 book ai didi

Java阻塞队列为什么我们在入队时有notifyall,条件是queue.size==0?

转载 作者:行者123 更新时间:2023-12-02 09:07:52 24 4
gpt4 key购买 nike

这是一个简单的实现:

  public synchronized void enqueue(Object item)throws InterruptedException  {
while(this.queue.size() == this.limit) {
wait();
}
if(this.queue.size() == 0) {
notifyAll();
}
this.queue.add(item);}

最佳答案

因为如果你看一下典型的出队,它看起来像这样

public synchronized Object dequeue() throws InterruptedException 
{
while (this.queue.size() == 0) {
wait(); // look here
}
if (this.queue.size() == this.limit) {
notifyAll();
}

return this.queue.remove(0);
}

通知队列大小为0时等待的锁。

关于Java阻塞队列为什么我们在入队时有notifyall,条件是queue.size==0?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59666919/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com