概念
定义
类似于Ajax,主要实现三个方法
- 异步执行
- 成功回调
- 失败回调
简单代码
// 发起一个请求 , 没有返回值的 runAsync 异步回调
CompletableFuture<Void> completableFuture = CompletableFuture.runAsync(()->{
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+" runAsync=>Void");
});
completableFuture.get(); //阻塞获取执行结果
// 发起一个请求 , 有返回值的 supplyAsync 异步回调
CompletableFuture<Integer> integerCompletableFuture = CompletableFuture.supplyAsync(() -> {
return 0;
});
//BiConsumer接口,lambda , 定义失败时
integerCompletableFuture.whenComplete((t,u)->{
// t是正常的返回结果
// u是错误信息(有的话)
}).exceptionally((e) -> { // Throwable 接口
System.out.println(e.getMessage());
//有异常则返回500
return 500;
});
Integer res = integerCompletableFuture.get();