【发布时间】:2016-08-26 15:09:16
【问题描述】:
您好,我认为使用 CompletableFuture 和默认的 ForkJoinPool 可以优化任务的执行,而不是经典的 ExecutorService,但我错过了一些东西
使用此代码执行需要 1 秒,我有 3 个工作线程:
for (int i = 0; i < 3; i++) {
final int counter = i;
listTasks.add(CompletableFuture.supplyAsync(() -> {
Thread.sleep(1000);
System.out.println("Looking up " + counter + " on thread " + Thread.currentThread().getName());
return null;
}));
}
好的,看起来很正常。
但是使用这段代码,需要 3 秒:
for (int i = 0; i < 9; i++) {
final int counter = i;
listTasks.add(CompletableFuture.supplyAsync(() -> {
Thread.sleep(1000);
System.out.println("Looking up " + counter + " on thread " + Thread.currentThread().getName());
return null;
}));
}
我认为睡眠线程将用于启动其他等待任务,它应该也需要 1 秒。例如,我读过 IO WAINTING 线程状态意味着该线程可以重用于其他任务。我可以用Thread.sleep() 测试这种行为吗?我的测试方法是错误的还是我理解错误?
【问题讨论】:
-
您的计算机上有多少个 CPU?
-
嗨,2 个真实的,但我将其设置为强制 3 个工作人员并避免产生线程:
System.setProperty("java.util.concurrent.ForkJoinPool.common.parallelism", "3"); -
很好的问题
标签: java multithreading asynchronous completable-future work-stealing