【发布时间】:2016-05-22 00:57:06
【问题描述】:
也许,一个新手问题,但它困扰着我,在一堆简单的教程和文档下,我没有找到答案。
问题。 在 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);
}
}
【问题讨论】:
-
我不完全理解你的问题,但看起来 ExecutorService/FutureTask 或 CyclicBarrier 是你要找的。span>
-
@VishalKamat,能否请您指出模糊的细节,以便解决问题。
标签: java multithreading threadpool executorservice