package com.company;
//异步回调
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
/**异步调用:CompletableFuture
* 异步执行-》成功回调-》失败回调
*/
public class AsynchronousCallback {
public static void main(String[] args) throws ExecutionException, InterruptedException {
//1、没有返回值的runAsync 异步调用
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");
//获得阻塞执行的结果
completableFuture.get();
//2、有返回值的SupplyAsync 异步回调
// CompletableFuture<Integer> completableFuture = new CompletableFuture<>().supplyAsync(()->{
// System.out.println(Thread.currentThread().getName()+"SupplyAsync=>Integer");
//
// int i = 10/0;
// return 1024;
// });
// System.out.println(completableFuture.whenComplete((t,u)->{
// System.out.println("t=>"+t); //正常的返回结果
// System.out.println("u=>"+u);//错误信息
// }).exceptionally((e)->{
// System.out.println(e.getMessage());
// return 233;
// }).get());
}
}
运行结果:
详细信息请看狂神视频