首页 文章

Java中的 生产环境 者/消费者模式

提问于
浏览
2

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

假设我有3个线程和一个包含任务的List(比如它是大约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的唯一方法吗?

1 回答

  • 3

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

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

相关问题