使用 CompletionStage 而不是 CompletableFuture

Ahm*_*lah 2 java lambda completable-future completion-stage

给出以下方法:

private static String getChuckNorrisJoke () {
    try {
        HttpURLConnection con = (HttpURLConnection) new
        URL( "http://api.icndb.com/jokes/random" ).openConnection();
        BufferedReader in = new BufferedReader( new InputStreamReader(con.getInputStream()));
        StringBuilder response = new StringBuilder();
        String line;
        while ((line = in.readLine()) != null ) {
            response.append(line);
        }
        in.close();
        return response.toString();
    } catch (IOException e) {
        throw new IllegalStateException( "Something is wrong: " , e);
    }
}
Run Code Online (Sandbox Code Playgroud)

以下语句可用于以异步方式运行该方法。

final CompletableFuture<String> jokeAsync = CompletableFuture.supplyAsync(() -> getChuckNorrisJoke());
Run Code Online (Sandbox Code Playgroud)

尽管我认为我理解CompletionStage与 的关系CompletableFuture,但我不确定如何使用它CompletionStage来完成相同的任务。

final CompletionStage<String> jokeAsync = ?
Run Code Online (Sandbox Code Playgroud)

另外,我不确定“组合阶段”

Did*_*r L 6

CompletionStage是由 实现的接口CompletableFuture,因此您只需声明jokeAsync为 aCompletionStage即可工作:

final CompletionStage<String> jokeAsync = CompletableFuture.supplyAsync(() -> getChuckNorrisJoke());
Run Code Online (Sandbox Code Playgroud)

如果您有多个阶段,您可以以不同的方式组合它们,例如:

CompletionStageAPI 不提供某些仅由 提供的操作CompletableFuture

  • 提交任务,例如supplyAsync()
  • 将多个阶段与allOf()和结合起来anyOf()
  • 以编程方式完成阶段或创建已完成的阶段
  • join()使用或等待阶段结果get()

但它toCompletableFuture()允许转换任何阶段,从而弥补差距。