CompletableFuture 异步获取结果
JDK1.8 提供的,用于弥补Future的重要不足点(get会阻塞)的一个类。大量用到了函数式编程的思想。
1. 对结果进行转换
supplyAsync() 对结果进行转换
返回一个新的CompletableFuture,异步去执行一个任务。
thenApplyAsync()
在上一个CompletableFuture 执行完毕之后再去执行一个新的CompletableFuture。
2. 直接把结果处理掉
thenAccept() 消费
String result = CompletableFuture.supplyAsync(() -> "hello").thenApplyAsync(value -> value + " world").join();
System.out.println(result);
System.out.println("========");
CompletableFuture.supplyAsync(() -> "hello").thenAccept(value -> System.out.println("welcome " + value));
System.out.println("========");
3. 对多个异步任务的结果合并
thenCombine()
// 对于stage的合并操作
String result2 = CompletableFuture.supplyAsync(() -> {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "hello";
}).thenCombine(CompletableFuture.supplyAsync(() -> {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "world";
}), (s1, s2) -> s1 + " " + s2).join();
System.out.println(result2);
whenComplete() 异步回调
CompletableFuture<Void> completableFuture = CompletableFuture.runAsync(() -> {
try {
TimeUnit.MILLISECONDS.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("task finished");
});
completableFuture.whenComplete((t, action) -> System.out.println("执行完成!"));
System.out.println("主线程执行完毕");
try {
TimeUnit.MILLISECONDS.sleep(7000);
} catch (InterruptedException e) {
e.printStackTrace();
}