JDK8新特性之CompletableFuture详解


文章参考链接:https://www.jianshu.com/p/547d2d7761db      https://www.jianshu.com/p/abfa29c01e1d

在JDK1.5已经提供了Future和Callable的实现,可以用于阻塞式获取结果,如果想要异步获取结果,通常都会以轮询的方式去获取结果,如下:

//定义一个异步任务
Future future = executor.submit(()->{
       Thread.sleep(2000);
       return "hello world";
});
//轮询获取结果
while (true){
    if(future.isDone()) {
         System.out.println(future.get());
         break;
     }
 }

从上面的形式看来轮询的方式会耗费无谓的CPU资源,而且也不能及时地得到计算结果.所以要实现真正的异步,上述这样是完全不够的。

而JDK1.8中的CompletableFuture就为我们提供了异步函数式编程,CompletableFuture提供了非常强大的Future的扩展功能,可以帮助我们简化异步编程的复杂性,提供了函数式编程的能力,可以通过回调的方式处理计算结果,并且提供了转换和组合CompletableFuture的方法。

1. 创建CompletableFuture对象

    CompletableFuture提供了四个静态方法用来创建CompletableFuture对象:

public static CompletableFuture   runAsync(Runnable runnable)  //异步不返回
public static CompletableFuture   runAsync(Runnable runnable, Executor executor)  //意思如下解释
public static  CompletableFuture  supplyAsync(Supplier supplier)  //异步返回一个结果
public static  CompletableFuture  supplyAsync(Supplier supplier, Executor executor)
 Asynsc表示异步,而supplyAsyncrunAsync不同在与前者异步返回一个结果,后者是void。第二个函数第二个参数表示是用我们自己创建的线程池,否则采用默认的ForkJoinPool.commonPool()作为它的线程池。而其中Supplier是一个函数式接口,代表是一个生成者的意思,传入0个参数,返回一个结果。(更详细的可以看我另一篇文章)
CompletableFuture future = CompletableFuture.supplyAsync(()->{
            return "hello world";
  });
System.out.println(future.get());  //阻塞的获取结果  ''helllo world"