CompletableFuture中 带后缀Async和不带后缀Async到底有什么区别?

先说结论:

先说结论:
以 thenRun 和 thenRunAsync 为例, 功能都是等待线程执行.
区别主要在线程池的使用上:
1.thenRun(Runnable action): 沿用上一个任务的线程池
2.thenRunAsync(Runnable action): 使用公用的 ForkJoinPool 线程池(不推荐使用公用线程池)
3.thenRunAsync(Runnable action,Executor executor): 使用自定义线程池(推荐)

实际开发推荐写法:使用自定义线程池

测试代码:

public class Test {
    /**
     * 有后缀 -Async 究竟有什么区别?
     * 以 thenRun 和 thenRunAsync 为例, 功能都是等待线程执行.
     * 区别主要在线程池的使用上:
     * thenRun(Runnable action): 沿用上一个任务的线程池
     * thenRunAsync(Runnable action): 使用公用的 ForkJoinPool 线程池(不推荐使用公用线程池)
     * thenRunAsync(Runnable action,Executor executor): 使用自定义线程池(推荐)
     */
    public static void main(String[] args) throws InterruptedException {
        ExecutorService executorService = Executors.newFixedThreadPool(1);
        //  使用自定义线程池(推荐)
        CompletableFuture<Void> a = CompletableFuture.runAsync(() -> {
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + ":runAsync: A.");
        }, executorService);

        // 沿用上一个任务的线程池
        thenRun(a);
        // 使用公用的 ForkJoinPool 线程池(不推荐使用公用线程池)
        thenRunAsync(a);

        System.out.println("main thread:" + Thread.currentThread().getName());
        // 主线程不能立马关闭, 否则子线程会直接中断
        Thread.sleep(1000);
        System.exit(0);
    }

    public static void thenRun(CompletableFuture<Void> a) {
        CompletableFuture<Void> b = a.thenRun(
                () -> System.out.println(Thread.currentThread().getName() + ":thenRun:B.")
        );
    }

    public static void thenRunAsync(CompletableFuture<Void> a) {
        CompletableFuture<Void> b = a.thenRunAsync(
                () -> System.out.println(Thread.currentThread().getName() + ":thenRunAsync:B.")
        );
    }
}

测试结果:

main thread:main
pool-1-thread-1:runAsync: A.
pool-1-thread-1:thenRun:B.
ForkJoinPool.commonPool-worker-9:thenRunAsync:B.

这三个方法,大家可以分别查看源码,就可以发现里面用的线程创建格式不一样。

关于CompletableFuture的基本用法,可以参考:

使用CompletableFuture优化你的代码执行效率

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值