參考:
1. 使用 runAsync()
運行異步計算
如果你想異步的運行一個后台任務並且不想改任務返回任務東西,這時候可以使用 CompletableFuture.runAsync()
方法,它持有一個Runnable 對象,並返回 CompletableFuture<Void>
。
// Run a task specified by a Runnable Object asynchronously.
CompletableFuture<Void> future = CompletableFuture.runAsync(new Runnable() { @Override public void run() { // Simulate a long-running Job try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { throw new IllegalStateException(e); } System.out.println("I'll run in a separate thread than the main thread."); } }); // Block and wait for the future to complete future.get()
2. 使用 supplyAsync()
運行一個異步任務並且返回結果
當任務不需要返回任何東西的時候, CompletableFuture.runAsync()
非常有用。但是如果你的后台任務需要返回一些結果應該要怎么樣?
CompletableFuture.supplyAsync()
就是你的選擇。它持有supplier<T>
並且返回CompletableFuture<T>
,T
是通過調用 傳入的supplier取得的值的類型。
// Run a task specified by a Supplier object asynchronously
CompletableFuture<String> future = CompletableFuture.supplyAsync(new Supplier<String>() {
@Override
public String get() { try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { throw new IllegalStateException(e); } return "Result of the asynchronous computation"; } }); // Block and get the result of the Future String result = future.get(); System.out.println(result);