CompletableFuture源码详解之java.util.concurrent.CompletableFuture#runAsync(java.lang.Runnable)
生活随笔
收集整理的這篇文章主要介紹了
CompletableFuture源码详解之java.util.concurrent.CompletableFuture#runAsync(java.lang.Runnable)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
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());} }?
執行結果如下圖:
?
轉載于:https://www.cnblogs.com/yangchangkui/p/10959260.html
總結
以上是生活随笔為你收集整理的CompletableFuture源码详解之java.util.concurrent.CompletableFuture#runAsync(java.lang.Runnable)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: apidoc学习(接口文档定义取代wor
- 下一篇: Java 10.switch语句