gpt4 book ai didi

java - Java中的生产者/消费者模式

转载 作者:行者123 更新时间:2023-12-04 06:17:25 25 4
gpt4 key购买 nike

我正在考虑如何在 Java 中实现生产者/消费者模式。

假设我有 3 个线程和一个包含任务的列表(比如说大约 5 个任务)。每个线程从列表中获取任务并同时执行它。我目前的方法是使用 CountDownLatch

int N = 3;
CountDownLatch startSignal = new CountDownLatch(1);
CountDownLatch doneSignal = new CountDownLatch(N);
ConcurrentLinkedQueue<String> tasks = new ConcurrentLinkedQueue<String>();

main() {
for (int i=0;i<N;i++) {
new Thread(new Worker()).start();
}
startSignal.countDown();
doneSignal.await();
System.out.println("done");
}

class Worker implements Runnable {
public void run() {
startSignal.await();
while ((s = tasks.poll()) != null) {
// do lengthy task here
if (task failed) {
tasks.add(s);
return; // assume that task fails badly and have to stop the thread
}
}
doneSignal.countDown();
}
}

我想要实现的是,如果线程在处理任务时失败,它将被添加回任务列表以由当前线程或任何其他线程再次拾取,但我目前使用 CountDownLatch 的方法显然不可能这样做是因为在调用 doneSignal.countDown() 之后,线程假定它已经完成了任务。

这种情况下最好的方法是什么?使用 Executor 是唯一的方法吗?

最佳答案

对于这种情况,我想说这是一个过于复杂(并且容易出错)的解决方案,使用通用的 BlockingQueue 会更简单,单线程从这个阻塞队列轮询并将作业移交给 ExecutorService。

看不出在这种情况下为什么需要 CountDownLatch 的任何原因,它只是不必要地使您的工作人员复杂化,必须了解它在线程环境中运行并且还必须在完成时清理任何脏东西。 BlockingQueues 和 ExecutorServices 正是为了让您摆脱这些问题。

关于java - Java中的生产者/消费者模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7061562/

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