CompletableFuture 实现了Future接口,Future最初的设计,是对将来的某个事件的返回结果进行建模。
没有返回值的异步回调,结果返回的是void ,适用于成功回调,不需要结果返回。
public static void main(String[] args) throws ExecutionException, InterruptedException {
//执行异步回调 无返回
CompletableFuture<Void> voidCompletableFuture = CompletableFuture.runAsync(() -> {
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "runAsync()");
});
//获取阻塞执行结果
voidCompletableFuture.get();
}
有返回结果的异步回调
package JUC.future;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
public class CompletobleFutureTest {
public static void main(String[] args) throws ExecutionException, InterruptedException {
//执行异步回调 无返回
/*CompletableFuture<Void> voidCompletableFuture = CompletableFuture.runAsync(() -> {
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "runAsync()");
});
//获取阻塞执行结果
voidCompletableFuture.get();*/
//执行失败回调 有返回值的异步
CompletableFuture<Integer> uCompletableFuture = CompletableFuture.supplyAsync(() -> {
int i = 10/0;
System.out.println(Thread.currentThread().getName() + "supplyAsync()");
return 1;
});
//编译完成时 执行成功 t 返回一个数字, u 为null ,失败的话t 为null,u为错误信息
System.out.println(uCompletableFuture.whenComplete((t, u) -> {
System.out.println("t :" + t);
System.out.println("u :" + u);
}).exceptionally((e) -> {
System.out.println(e.getMessage());
return 500;
}).get());
}
}