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


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