相关疑难解决方法(0)

如何使用CompletableFuture.thenComposeAsync()?

鉴于:

public class Test
{
    public static void main(String[] args)
    {
        int nThreads = 1;
        Executor e = Executors.newFixedThreadPool(nThreads);

        CompletableFuture.runAsync(() ->
        {
            System.out.println("Task 1. Thread: " + Thread.currentThread().getId());
        }, e).thenComposeAsync((Void unused) ->
        {
            return CompletableFuture.runAsync(() ->
            {
                System.out.println("Task 2. Thread: " + Thread.currentThread().getId());
            }, e);
        }, e).join();
        System.out.println("finished");
    }
}
Run Code Online (Sandbox Code Playgroud)

我期待一个执行程序线程运行任务1,然后执行任务2.相反,代码挂起,如果nThreads小于2.

  1. 请解释代码挂起的原因.我可以看到它在CompletableFuture中被阻止:616等待一些Future完成,但目前尚不清楚原因.
  2. 如果我允许使用2个线程,那么每个线程用于什么?

总之,请帮助我了解thenComposeAsync()实际工作原理.Javadoc看起来像是为机器人而不是人类而写的:)

java multithreading future java-8

7
推荐指数
2
解决办法
4294
查看次数

标签 统计

future ×1

java ×1

java-8 ×1

multithreading ×1