编程语言
首页 > 编程语言> > Java8新特性之 CompletableFuture方法详解

Java8新特性之 CompletableFuture方法详解

作者:互联网

  CompletableFuture 提供了四个静态方法来创建一个异步操作。

  静态方法如下:

  CompletableFuture runAsync(Runnable runnable);

  CompletableFuture runAsync(Runnable runnable, Executor executor);

  CompletableFuture supplyAsync(Supplier supplier);

  CompletableFuture supplyAsync(Supplier supplier, Executor executor);

  runAsync 与 supplyAsync 两者区别:

  runAsync方法不支持返回值。

  supplyAsync可以支持返回值。

  Executor说明:

  如果方法存在executor参数,就使用executor执行任务;

  否则默认使用公用的ForkJoinPool.commonPool()作为执行异步任务的线程池。

  示例一

  public static void main(String[] args) throws ExecutionException, InterruptedException {

  CompletableFuture future = CompletableFuture.runAsync(() -> System.out.println("Hello World"));

  System.out.println(future.get());

  }

  执行结果:

  Hello World

  null

  示例二

  public static void main(String[] args) throws ExecutionException, InterruptedException {

  ExecutorService executor = Executors.newCachedThreadPool();

  CompletableFuture future = CompletableFuture.runAsync(() -> System.out.println("Hello World"),executor);

  System.out.println(future.get());

  }郑州人流医院 http://www.zyfuke.com/

  执行结果:

  Hello World

  null

  示例三

  public static void main(String[] args) throws ExecutionException, InterruptedException {

  // 获取当前时间戳

  CompletableFuture future = CompletableFuture.supplyAsync(System::currentTimeMillis);

  System.out.println(future.get());

  }

  执行结果:

  1586245295714

  示例四

  public static void main(String[] args) throws ExecutionException, InterruptedException {

  // 获取当前时间戳

  ExecutorService executor = Executors.newCachedThreadPool();

  CompletableFuture future = CompletableFuture.supplyAsync(System::currentTimeMillis,executor);

  System.out.println(future.get());

  }

  执行结果:

  1586245295714


标签:System,runAsync,future,CompletableFuture,executor,Java8,详解,out
来源: https://blog.51cto.com/14335413/2485738