CompletableFuture#runAsync方法是用來執行無返回結果的異步程序,當執行一大堆業務邏輯代碼,而又不需要返回結果的時候,可以使用此方法異步執行,提升接口性能,方法源碼如下:
/** * Returns a new CompletableFuture that is asynchronously completed * by a task running in the {@link ForkJoinPool#commonPool()} after * it runs the given action. * * @param runnable the action to run before completing the * returned CompletableFuture * @return the new CompletableFuture */ public static CompletableFuture<Void> runAsync(Runnable runnable) { return asyncRunStage(asyncPool, runnable); }
源碼所示,任務使用的是 ForkJoinPool#commonPool() 線程池執行,后續會寫這塊的內容,具體使用實例如下:
import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; /** * 測試類 * @author yangchangkui */ public class TestMy { public static void main(String[] args) throws ExecutionException, InterruptedException { long start = System.currentTimeMillis(); CompletableFuture<Void> voidCompletableFuture = CompletableFuture.runAsync(() -> { try { //do something ... Thread.sleep(300); } catch (InterruptedException e) { e.printStackTrace(); } }); //判斷是否已經完成 System.out.println("耗時1:"+(System.currentTimeMillis()-start)+",isDone:"+voidCompletableFuture.isDone()); //do something ... Thread.sleep(300); //判斷是否已經完成 System.out.println("耗時2:"+(System.currentTimeMillis()-start)+",isDone:"+voidCompletableFuture.isDone()); } }
執行結果如下圖: