在Java中CompletableFuture用于异步编程,异步编程是编写非阻塞的代码,运行的任务在一个单独的线程,与主线程隔离,并且会通知主线程它的进度,成功或者失败。
在这种方式中,主线程不会被阻塞,不需要一直等到子线程完成。主线程可以并行的执行其他任务。
使用这种并行方式,可以极大的提高程序的性能。
一般应用场景:在业务开发中可能会遇到调用多个第三方接口,同时要求主流程不被阻塞。
public static void main(String[] args) throws Exception {// 开启一个线程(无返回值)CompletableFuture<Void> voidCompletableFuture = CompletableFuture.runAsync(() -> {try {TimeUnit.SECONDS.sleep(3);} catch (InterruptedException e) {throw new RuntimeException(e);}});// 开启一个线程(有返回值)CompletableFuture<Integer> integerCompletableFuture = CompletableFuture.supplyAsync(() -> {try {Thread.sleep(3);return 1;} catch (InterruptedException e) {throw new RuntimeException(e);}});{// do things}// 等待异步现成执行完CompletableFuture.allOf(integerCompletableFuture).get();// 等待多个异步现成执行完CompletableFuture.allOf(voidCompletableFuture,integerCompletableFuture).get();// 打印异步结果System.out.println(integerCompletableFuture.get());System.out.println("over");}