12.Future异步回调
Future异步回调
Future设计的初衷,对将来的某个时间的结果进行建模
/*
异步调用 CompletableFuture
异步执行,成功回调,失败回调
*输出结果:
111111111
ForkJoinPool.commonPool-worker-1runAsync void
* */
public class Demo01 {
public static void main(String[] args) throws Exception {
//test1();//无返回值的
test2();//有返回值的
}
//无返回值的异步回调
public static void test1() throws ExecutionException, InterruptedException {
//发起一个请求,没有返回值的异步回调
CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "runAsync void");
});
System.out.println(111111111);
//阻塞 获取执行结果
future.get();
}
//有返回值的异步回调,有成功,有失败
//ajax success fail
public static void test2() throws ExecutionException, InterruptedException {
CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
System.out.println(Thread.currentThread().getName() + "supplyAsync==》Integer");
//int i = 2 / 0;
return 1024;//成功返回1024
});
System.out.println(future.whenComplete((t, u) -> {
System.out.println("t==" + t);//正常的返回结果
System.out.println("u==" + u);//错误信息
}).exceptionally((e) -> {//失败
System.out.println(e.getMessage());
return 123;//失败返回233
}).get());
}
}

浙公网安备 33010602011771号