给出以下方法:
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)