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