thenApply()和handle()的区别就是异常的处理方式不同
public static void main(String[] args) {
Integer result = CompletableFuture.supplyAsync(() -> {
return 1;
}, executor).thenApply((f -> {
return f + 2;
})).thenApply(f -> {
return f + 3;
}).thenApply(f -> {
return f + 4;
}).whenComplete((v, e) -> {
if (e == null) {
System.out.println("=== result: " + v);
}
}).exceptionally(e -> {
e.printStackTrace();
System.out.println(e.getMessage());
return null;
}).join();
executor.shutdown();
}
xxx() 和 xxxAsync() 的区别,一般用xxx()
thenAccept()和thenApply()就是有无返回值的区别
最快返回输出的线程结果作为下一次任务的输入
public static void main(String[] args) {
Integer join = CompletableFuture.supplyAsync(() -> {
try { TimeUnit.SECONDS.sleep(3); } catch (InterruptedException e) { e.printStackTrace(); }
return 3;
}, executor).applyToEither(CompletableFuture.supplyAsync(() -> {
try { TimeUnit.SECONDS.sleep(2); } catch (InterruptedException e) { e.printStackTrace(); }
return 2;
}), r -> {
return r;
}).applyToEither(CompletableFuture.supplyAsync(()->{
try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); }
return 1;
}), r ->{
return r;
}).join();
// 哪个线程跑的最快用那个
System.out.println(join); // 1
}
thenCombine对计算结果进行合并
public static void main(String[] args) {
Integer join = CompletableFuture.supplyAsync(() -> {
return 10;
}).thenCombine(CompletableFuture.supplyAsync(() -> {
return 20;
}), (r1, r2) -> {
return r1 + r2;
}).join();
System.out.println(join); // 30
}
进微信群和大佬面对面学习交流