Java CompletableFuture的thenApply和thenApplyAsync有什么区别? [英] What is the difference between thenApply and thenApplyAsync of Java CompletableFuture?

查看:8571
本文介绍了Java CompletableFuture的thenApply和thenApplyAsync有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有以下代码:

CompletableFuture<Integer> future  
        = CompletableFuture.supplyAsync( () -> 0);

thenApply 案例:

future.thenApply( x -> x + 1 )
      .thenApply( x -> x + 1 )
      .thenAccept( x -> System.out.println(x));

这里输出为2.现在是 thenApplyAsync

Here the output will be 2. Now in case of thenApplyAsync:

future.thenApplyAsync( x -> x + 1 )   // first step
      .thenApplyAsync( x -> x + 1 )   // second step
      .thenAccept( x -> System.out.println(x)); // third step

我在这里读到了博客每个 thenApplyAsync 在一个单独的线程中执行'同时'(这意味着跟随 thenApplyAsyncs 之前启动,然后是ApplyAsyncs 完成),如果是这样,输入是什么如果第一步没有完成,第二步的参数值是什么?

I read in this blog that each thenApplyAsync are executed in a separate thread and 'at the same time'(that means following thenApplyAsyncs started before preceding thenApplyAsyncs finish), if so, what is the input argument value of the second step if the first step not finished?

如果第二步没有采取第一步的结果将在哪里?
第三步将采取哪一步结果?

Where will the result of the first step go if not taken by the second step? the third step will take which step's result?

如果第二步必须等待第一步的结果那么异步

If the second step has to wait for the result of the first step then what is the point of Async?

这里x - > x + 1只是为了表明这一点,我想知道的是在非常长的计算。

Here x -> x + 1 is just to show the point, what I want know is in cases of very long computation.

推荐答案

区别与执行者有关负责运行代码。 CompletableFuture 上的每个运营商通常有3个版本。

The difference has to do with the Executor that is responsible for running the code. Each operator on CompletableFuture generally has 3 versions.


  1. thenApply(fn) - 在由 CompleteableFuture 定义的线程上运行 fn 被调用,所以你通常不知道这将被执行的地方。如果结果已经可用,它可能立即执行。

  2. thenApplyAsync(fn) - 运行 fn 在环境定义的执行程序上,无论情况如何。对于 CompletableFuture ,这通常是 ForkJoinPool.commonPool()

  3. thenApplyAsync(fn,exec) - 在 exec 上运行 fn

  1. thenApply(fn) - runs fn on a thread defined by the CompleteableFuture on which it is called, so you generally cannot know where this will be executed. It might immediately execute if the result is already available.
  2. thenApplyAsync(fn) - runs fn on a environment-defined executor regardless of circumstances. For CompletableFuture this will generally be ForkJoinPool.commonPool().
  3. thenApplyAsync(fn,exec) - runs fn on exec.

最后结果相同,但调度行为取决于方法的选择。

In the end the result is the same, but the scheduling behavior depends on the choice of method.

这篇关于Java CompletableFuture的thenApply和thenApplyAsync有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆