CompletableFuture 在 Java 里面被用于异步编程,异步通常意味着非阻塞,
可以使得我们的任务单独运行在与主线程分离的其他线程中,并且通过回调可
以在主线程中得到异步任务的执行状态,是否完成,和是否异常等信息。
CompletableFuture 实现了 Future, CompletionStage 接口,实现了 Future
接口就可以兼容现在有线程池框架,而 CompletionStage 接口才是异步编程
的接口抽象,里面定义多种异步方法,通过这两者集合,从而打造出了强大的
CompletableFuture 类。
import java.util.concurrent.CompletableFuture; /** * @author zhang.rongshan * @create 2022-01-05 上午12:04 */ //异步调用和同步调用 public class CompletableFutureDemo { public static void main(String[] args) throws Exception { //同步调用 CompletableFuture<Void> completableFuture1 = CompletableFuture.runAsync(()->{ System.out.println(Thread.currentThread().getName()+" : CompletableFuture1"); }); completableFuture1.get(); //mq消息队列 //异步调用 CompletableFuture<Integer> completableFuture2 = CompletableFuture.supplyAsync(()->{ System.out.println(Thread.currentThread().getName()+" : CompletableFuture2"); //模拟异常 // int i = 10/0; return 1024; }); completableFuture2.whenComplete((t,u)->{ System.out.println("------t="+t);//返回值 System.out.println("------u="+u);//异常 }).get(); } }