首页 > 编程语言 > 详细

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

时间:2019-06-01 13:28:51      阅读:230      评论:0      收藏:0      [点我收藏+]

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

 

执行结果如下图:

技术分享图片

 

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

原文:https://www.cnblogs.com/yangchangkui/p/10959260.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!