CompletableFuture源码详解之java.util.concurrent.CompletableFuture#runAsync(java.lang.Runnable) - 行云(xingyun) - 博客园

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

}

复制代码; "复制代码")

执行结果如下图:


原网址: 访问
创建于: 2021-02-23 18:23:53
目录: default
标签: 无

请先后发表评论
  • 最新评论
  • 总共0条评论