Future 异步回调
异步调用
/*异步调用
* ajax: 客户端服务器
* future: java类CompletableFuture<T>
* 1. 异步执行
* 2. 成功回调
* 3. 失败回调*/
public class Demo01 {
public static void main(String[] args) throws ExecutionException, InterruptedException {
/* //发起一个请求 没有返回值的异步回调
CompletableFuture<Void> completableFuture = CompletableFuture.runAsync(()->{
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+" runAsync=>Void");
});
System.out.println("1111"); //立刻输出
Void aVoid = completableFuture.get();//获取执阻塞行结果 异步输出*/
//发起一个请求 有返回值的异步回调
/*
* 失败时返回错误信息*/
CompletableFuture<Integer> completableFuture = CompletableFuture.supplyAsync(() -> {
// int i=10/0; //故意制造错误信息
System.out.println(Thread.currentThread().getName()+" runAsync=>Void");
return 1024;
});
System.out.println(completableFuture.whenComplete((t, u) -> {
System.out.println("t->" + t); //正常的返回结果
System.out.println("u->" + u);
}).exceptionally((e) -> {
e.getMessage();
return 2333;
}).get());
}
}
//错误结果
/*
t->null
u->java.util.concurrent.CompletionException: java.lang.ArithmeticException: / by zero
2333
*/
//成功结果
/*
ForkJoinPool.commonPool-worker-9 runAsync=>Void
t->1024
u->null
1024
*/