一、概述
二、案例代码
/**
* @Author : 一叶浮萍归大海
* @Date: 2023/11/21 10:45
* @Description: 异步任务案例代码
*/
public class CompletableFutureMainApp {
public static void main(String[] args) throws ExecutionException, InterruptedException {
CompletableFuture<Void> future1 = CompletableFuture.runAsync(() -> {
System.out.println(Thread.currentThread().getName() + "\t future1");
});
System.out.println("future1.get() = " + future1.get());
CompletableFuture<Integer> future2 = CompletableFuture.supplyAsync(() -> {
System.out.println(Thread.currentThread().getName() + "\t future2");
// int i = 10 / 0;
return 1024;
});
Integer result = future2.whenComplete((t, u) -> {
System.out.println("============>t:" + t);
System.out.println("============>u:" + u);
}).exceptionally(f -> {
System.out.println("============>exception:" + f.getMessage());
return 444;
}).get();
System.out.println("result = " + result);
}
}