FixedThreadPool 执行器受某些终止条件限制

FixedThreadPool executor limited by some termination condition

也许,一个新手问题,但它困扰着我,在一堆简单的教程和文档中,我没有找到我的答案。

问题。 在 Java 中使用来自 JDK(1.8) 的高级并行模式来实现下一个的最佳方法是什么?一个固定的 N 线程池正在执行相同的预定义任务,直到达到终止条件。因此,任务的数量不是预先定义的,条件是外部实时触发器。我们必须急切地对终止做出反应,但不要消耗太多资源切换上下文并从工作线程窃取 CPU 时间。比方说,我们只有两到四个弱物理线程要在控制线程上花费很多。

如果有帮助,当前的想法将在下一个代码中实现,但是动态任务队列,而大部分睡眠控制周期对我来说看起来不够简洁。

try {
    mainCycle(agent, executor, terminationCondition);
} catch (InterruptedException e) {
    log.warn(INTERRUPTED_EX, e);
} finally {
    executor.shutdownNow();
}

 private static void mainCycle(Callable<Long> agent,
                                  ExecutorService executor,
                                  Supplier<Boolean> terminationCondition
) throws InterruptedException {

    final List<Future<Long>> runFutureResults = executor.
            invokeAll(Collections.nCopies(parallelAgents, agent));

    int tasksReserve = BASE_MULTIPLIER;
    //noinspection MethodCallInLoopCondition, by design
    while (!terminationCondition.get()) {
        tasksReserve = addTasksIfNeed(executor, runFutureResults);
        Thread.sleep(1000);
    }
}

要么使用某种协调机制(phaser,在 Java 7 中引入,当您需要动态添加更多作业时很有用),要么只保留您设置的外部标志完成后:

ExecutorService service = Executors.newFixedThreadPool(N);
volatile boolean done = false;

// add your jobs:
service.submit(() -> {
    while (!done) {
        // do something
    }
});

// set your flag
done = true;

标志是可变的就足够了,因为只有一个线程改变值;执行程序中的线程只需要了解它何时更改。