在 ForkJoinpool 上使用 CompletableFuture 并避免线程等待

bod*_*dtx 5 java multithreading asynchronous work-stealing completable-future

你好,我认为使用 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;
    }));
}
Run Code Online (Sandbox Code Playgroud)

好吧,看起来很正常。

但是使用此代码,需要 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;
    }));
}
Run Code Online (Sandbox Code Playgroud)

我认为睡眠线程将用于启动其他等待任务,它也应该需要 1 秒。例如,我读过 IO WAINTING 线程状态意味着该线程可以重用于其他任务。我可以用 测试这种行为Thread.sleep()吗?我的测试方法是错误的还是我理解错了?

And*_*gin 5

睡眠线程不能用于执行另一个线程的工作(特别是,一个线程不能为另一个线程睡眠)。当第一个线程进入睡眠状态时,只有 CPU 可以切换到第二个线程。

当您向 提供任务时CompletableFuture.supplyAsync(),它会转到 的默认实例,ForkJoinPool该实例的线程数与您计算机的 CPU 数相同。您手动将分配的三个线程设置为默认值ForkJoinPool,因此您的九个任务在它们之间平均分配:每个线程连续执行三个任务。所以,你有三秒钟的时间得出结果。