简体   繁体   English

使用CompletionStage而不是CompletableFuture

[英]using CompletionStage instead of CompletableFuture

given the following method: 给出以下方法:

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);
    }
}

the following statement can be used to run the method in an asynchronous fashion. 以下语句可用于以异步方式运行该方法。

final CompletableFuture<String> jokeAsync = CompletableFuture.supplyAsync(() -> getChuckNorrisJoke());

although I think that I understand CompletionStage relation to CompletableFuture , I am not sure how I can use CompletionStage to accomplish same task. 尽管我认为我了解CompletionStageCompletableFuture关系,但是我不确定如何使用CompletionStage完成相同的任务。

final CompletionStage<String> jokeAsync = ?

also, I am not sure about "combining stages" 另外,我不确定“合并阶段”

CompletionStage is the interface implemented by CompletableFuture , so you can just declare jokeAsync as a CompletionStage and it will work: CompletionStage是由CompletableFuture实现的接口,因此您只需将jokeAsync声明为CompletionStage使用:

final CompletionStage<String> jokeAsync = CompletableFuture.supplyAsync(() -> getChuckNorrisJoke());

If you have several stages, you can combine them in different ways, like: 如果您有多个阶段,则可以采用不同的方式将它们组合在一起,例如:

The CompletionStage API does not offer some operations that are only provided by CompletableFuture : CompletionStage API不提供一些仅由CompletableFuture提供的操作:

  • submitting tasks, eg with supplyAsync() 提交任务,例如使用supplyAsync()
  • combining many stages with allOf() and anyOf() 将许多阶段与allOf()anyOf()
  • programmatically completing stages or creating already completed stages 以编程方式完成阶段或创建已经完成的阶段
  • waiting for a stage's result with join() or get() join()get()等待阶段的结果

But the toCompletableFuture() allows to convert any stage and thus bridge the gap. 但是toCompletableFuture()允许转换任何阶段,从而缩小差距。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM