糖尿病康复,内容丰富有趣,生活中的好帮手!
糖尿病康复 > CompletableFuture源码详解之java.util.concurrent.CompletableFuture#runAsync(java.lang.Runnable)

CompletableFuture源码详解之java.util.concurrent.CompletableFuture#runAsync(java.lang.Runnable)

时间:2023-06-11 21:17:55

相关推荐

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.pletableFuture;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());}}

执行结果如下图:

如果觉得《CompletableFuture源码详解之java.util.concurrent.CompletableFuture#runAsync(java.lang.Runnable)》对你有帮助,请点赞、收藏,并留下你的观点哦!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。