所謂異步調用其實就是實現一個可無需等待被調用函數的返回值而讓操作繼續運行的方法。Java中的CompletableFuture 提供了四個靜態方法來創建一個異步操作。
1 public static CompletableFuture<Void> runAsync(Runnable runnable) 2 public static CompletableFuture<Void> runAsync(Runnable runnable, Executor executor) 3 public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier) 4 public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier, Executor executor)
沒有指定Executor的方法會使用ForkJoinPool.commonPool() 作為它的線程池執行異步代碼。如果指定線程池,則使用指定的線程池運行。其中:
runAsync方法不支持返回值。
supplyAsync可以支持返回值。
如下:
//無返回值 public static void runAsync() throws Exception { CompletableFuture<Void> future = CompletableFuture.runAsync(() -> { try { System.out.println("run start ..."); TimeUnit.SECONDS.sleep(5); } catch (InterruptedException e) { } System.out.println("run end ..."); }); future.get(); } //有返回值 public static void supplyAsync() throws Exception { CompletableFuture<Long> future = CompletableFuture.supplyAsync(() -> { try { System.out.println("run start ..."); TimeUnit.SECONDS.sleep(5); } catch (InterruptedException e) { } System.out.println("run end ..."); return System.currentTimeMillis(); }); long time = future.get(); System.out.println("time = "+time); }
今天寫到這里,簡單的使用如上代碼,后續會有更新。
