异步回调
异步回调
很像ajax
package com.luoKing.future;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
public class Demo {
public static void main(String[] args) throws ExecutionException, InterruptedException {
// //没有返回值的异步回调
// CompletableFuture<Void> completableFuture =CompletableFuture.runAsync(()->{
// System.out.println(Thread.currentThread().getName()+"->runAsync");
// });
//
// System.out.println("11111");
// completableFuture.get();//获取异步执行结果
//有返回值的异步调用
CompletableFuture<Integer> completableFuture2 =CompletableFuture.supplyAsync(()->{
int sum = 10/0;
return 1024;
});
System.out.println(completableFuture2.whenComplete((t, u) -> {
System.out.println("t->" + t); //t输出回调正确的信息
System.out.println("u->" + u); //u输出异常信息 java.util.concurrent.CompletionException:
}).exceptionally((e) -> {
System.out.println(e.getMessage());
return 500;//当发生错误回调时,就会输出这里的返回值
}).get());
}
}