gpt4 book ai didi

java - 混淆了一个简单的生产者 - 消费者实现同步,等待,notifyAll

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:00:20 27 4
gpt4 key购买 nike

在我的代码中,当生产者线程需要在生产者代码中等待时,我在 while 循环中尝试了两个类似的条件代码来检查复选框是否已满。但它的输出是不同的,我很困惑。

错误是当我使用名为“大小”的变量在线程的运行代码中保存框大小的值时。在某些情况下,程序会像死一样阻塞。

生产者代码:

public class Producer implements Runnable{
private final List<String> boxes;
private final int MAX_SIZE = 5;
public Producer(List<String> aboxes) {
super();
this.boxes = aboxes;
}
@Override
public void run() {
while (true) {
synchronized (boxes) {
try {
int size = boxes.size(); // OR int size = this.boxes.size();

// while(MAX_SIZE == this.boxes.size()) { OK
// while(MAX_SIZE == boxes.size()) { OK
while (MAX_SIZE == size) { // ERROR
boxes.wait();
}

Thread.sleep(500);
String product = "product : " + UUID.randomUUID().toString();
boxes.add(product);

boxes.notifyAll();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}

最佳答案

当前情况下 while 语句中的条件是静态的,即对于 MAX_SIZE == size,当再次评估 while 循环时,两个变量的值都不会改变。

当在 boxes 上调用 notify 并通知生产者线程时,while 循环将再次计算。由于两个值都没有改变,它们的值都将为 5,并且在评估循环时,它的值将再次为 5。所以 while 条件将是 5==5 导致 wait 被再次调用。即一旦进入while循环,条件将一直为true,导致无限阻塞。

但是在条件 MAX_SIZE == boxes.size() 的情况下,boxes.size() 的值是动态的,它会被改变,我猜这里的消费者.比方说,消费者从此列表中删除一个元素 boxes.size()=4 并在 boxes 上调用 notify。因此,生产者线程收到通知,producer 中的条件变为 5 == 4,这导致 while 条件为 false 并退出循环。因此代码按预期执行

关于java - 混淆了一个简单的生产者 - 消费者实现同步,等待,notifyAll,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55673348/

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