gpt4 book ai didi

java - 生产者/消费者线程并发 Java

转载 作者:行者123 更新时间:2023-12-01 22:43:27 25 4
gpt4 key购买 nike

我有一个生产产品的生产者和一个消费产品的消费者。我想要的是,如果产品在 5 分钟内没有被消耗,我希望它被销毁。

这是生产者的部分:

boolean full = false;
public void produce(int p) throws RemoteException {
//choses a or b randomly
//if a or b spot is occupied, thread must wait()

synchronized(this){
if ((int)((Math.random()*10)%2) == 1){
while (a!=-1){try {
wait();
} catch (InterruptedException ex) {
Logger.getLogger(CHServer.class.getName()).log(Level.SEVERE, null, ex);
}
}
a = p;
if (b!=-1) full = true;
notifyAll();
}
else {
while (b!=-1){try {
wait();
} catch (InterruptedException ex) {
Logger.getLogger(CHServer.class.getName()).log(Level.SEVERE, null, ex);
}
}
b = p;
if (a!=-1) full = true;
notifyAll();
}
}
}

a 和 b 应该是我的产品。

我真的不知道如何测量该时间,例如当线程正在等待或客户端没有尝试使用该产品时。这段代码运行在 RMI java 服务器上。

最佳答案

我只是使用这样的方案:当您生成某些内容时,使用 java.util.Timer() 来设置 future 5 分钟的计时器。当元素被消耗时,.cancel() 计时器。如果计时器响了,请执行您需要执行的任何清理操作。

关于java - 生产者/消费者线程并发 Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25731738/

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