[英]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. 尽管我认为我了解CompletionStage
与CompletableFuture
关系,但是我不确定如何使用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: 如果您有多个阶段,则可以采用不同的方式将它们组合在一起,例如:
thenCombine()
to combine the result of 2 stages thenCombine()
合并两个阶段的结果 applyToEither()
to process the result of the first one that completes and return a new stage with the result applyToEither()
处理第一个完成的结果,并返回带有结果的新阶段 acceptEither()
to consume the result of either without returning a new result acceptEither()
可以使用任一结果而不返回新结果 runAfterBoth()
and runAfterEither()
to run an operation after both or either stage is completed. runAfterBoth()
和runAfterEither()
在两个阶段或两个阶段均完成之后运行操作。 The CompletionStage
API does not offer some operations that are only provided by CompletableFuture
: CompletionStage
API不提供一些仅由CompletableFuture
提供的操作:
supplyAsync()
提交任务,例如使用supplyAsync()
allOf()
and anyOf()
将许多阶段与allOf()
和anyOf()
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.