JUC之异步编排和并行优化

在某个业务接口中,系统需要调用B、C、D的接口,常规我们可能这样写

@SpringBootTest
public class Thread {

    @Test
    void demo1() throws InterruptedException {
        long startTime = System.currentTimeMillis();
        // 调用三个系统
        method1();
        method2();
        method3();
        long endTime = System.currentTimeMillis();
        System.out.println("执行时间:" + (endTime - startTime) + "毫秒");
    }
    // 模拟
    public static void method1() throws InterruptedException {
        TimeUnit.MILLISECONDS.sleep(100);
    }
    public static void method2() throws InterruptedException {
        TimeUnit.MILLISECONDS.sleep(200);
    }
    public static void method3() throws InterruptedException {
        TimeUnit.MILLISECONDS.sleep(300);
    }

}

运行后结果如下
在这里插入图片描述
总耗时为BCD三个系统接口请求时间之和。
我们可以通过线程池来进行并行处理,使总耗时变为BCD三个系统中耗时最长的那个,也就是300毫秒,改造如下demo2():

 @Test
    void demo2(){
        // 创建线程池
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(10, 15, 1L, TimeUnit.SECONDS, new LinkedBlockingQueue<>(30));
        long startTime = System.currentTimeMillis();
        // 使用异步任务
        CompletableFuture<Void> customerInfoFuture1 = CompletableFuture.runAsync(() -> {
            try {
                method1();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }, threadPoolExecutor);
        CompletableFuture<Void> customerInfoFuture2 = CompletableFuture.runAsync(() -> {
            try {
                method2();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }, threadPoolExecutor);
        CompletableFuture<Void> customerInfoFuture3 = CompletableFuture.runAsync(() -> {
            try {
                method3();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }, threadPoolExecutor);
        // 等待所有任务完成
        CompletableFuture.allOf(customerInfoFuture1, customerInfoFuture2, customerInfoFuture3).join();

        long endTime = System.currentTimeMillis();
        System.out.println("执行时间:" + (endTime - startTime) + "毫秒");
    }

执行结果如下:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值