![](/img/trans.png)
[英]Difference between a ExecutorCompletionService and a FixedThreadPool executor
[英]FixedThreadPool executor limited by some termination condition
也許這是一個新手問題,但它困擾了我,在一堆簡單的教程和文檔中,我沒有找到答案。
題。 使用JDK(1.8)中的高級並行模式來實現下一個Java 的最佳方法是什么? 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);
}
}
使用某種協調機制(當您需要動態添加更多作業時,Java 7中引入的phaser很有用),或者只是保留完成時設置的外部標志:
ExecutorService service = Executors.newFixedThreadPool(N);
volatile boolean done = false;
// add your jobs:
service.submit(() -> {
while (!done) {
// do something
}
});
// set your flag
done = true;
因為只有一個線程正在修改該值,所以該標志是可變的就足夠了; 執行器內部的線程只需要了解它何時更改。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.