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


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章