目前要使用 CompletionStage 的集合做一些简单的事情需要跳过几个难看的圈子:
public static CompletionStage<String> translate(String foo) {
// just example code to reproduce
return CompletableFuture.completedFuture("translated " + foo);
}
public static CompletionStage<List<String>> translateAllAsync(List<String> input) {
List<CompletableFuture<String>> tFutures = input.stream()
.map(s -> translate(s)
.toCompletableFuture())
.collect(Collectors.toList()); // cannot use toArray because of generics Arrays creation :-(
return CompletableFuture.allOf(tFutures.toArray(new CompletableFuture<?>[0])) // not using size() on purpose, see comments
.thenApply(nil -> tFutures.stream()
.map(f -> f.join())
.map(s -> s.toUpperCase())
.collect(Collectors.toList()));
}
Run Code Online (Sandbox Code Playgroud)
我想写的是:
public CompletionStage<List<String>> translateAllAsync(List<String> input) {
// allOf takes a collection< futures<X>>, …
Run Code Online (Sandbox Code Playgroud) 这是我面临的问题的简短代码版本:
public static void main(String[] args) {
CompletableFuture.supplyAsync(() -> {
/*
try {
Thread.sleep(2000);
} catch (InterruptedException ignored) {}
*/
//System.out.println("supplyAsync: " + Thread.currentThread().getName());
return 1;
})
.thenApply(i -> {
System.out.println("apply: " + Thread.currentThread().getName());
return i + 1;
})
.thenAccept((i) -> {
System.out.println("accept: " + Thread.currentThread().getName());
System.out.println("result: " + i);
}).join();
}
Run Code Online (Sandbox Code Playgroud)
这是我得到的输出:
apply: main
accept: main
result: 2
Run Code Online (Sandbox Code Playgroud)
看到main
那里我很惊讶!Thread.sleep()
我预计当我取消注释该调用或什至取消注释单个语句时会发生类似的情况sysout
:
supplyAsync: ForkJoinPool.commonPool-worker-1
apply: ForkJoinPool.commonPool-worker-1
accept: ForkJoinPool.commonPool-worker-1
result: 2
Run Code Online (Sandbox Code Playgroud)
我理解thenApplyAsync()
将确保它不会在main
线程上运行,但我想避免将供应商从运行的线程返回的数据传递supplyAsync …
java multithreading asynchronous 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) 这是我的简单代码:
public class Main4 {
public static void main(String[] args) {
System.out.println("Hello from thread: "+Thread.currentThread().getName());
new Game().run();
System.out.println("I am dying ... ");
}
static class Game {
public void run() {
value();
}
private int value() {
int number = 0;
CompletionStage<Void> c = calculate().thenApply(i -> i + 3).thenAccept(i -> System.out.println("I am done, and my value is " + i));
return number;
}
private CompletionStage<Integer> calculate() {
CompletionStage<Integer> completionStage = new CompletableFuture<>();
Executors.newCachedThreadPool().submit(() -> {
System.out.println("I am in the thread: …
Run Code Online (Sandbox Code Playgroud) java multithreading threadpool completable-future completion-stage
只是浏览CompletableFuture
文档并偶然发现了completeExceptionally
和obtrudeException
方法,并且很难理解差异和用例。社区可以通过示例帮助理解差异和用例吗?
java multithreading asynchronous completable-future completion-stage