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

 

执行结果如下图:

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM