CompletableFuture

CompletableFuture.allOf(task1, task2).join() 等待所有异步任务完成

异步任务:
// 异步任务task1 && task2
@Component
public class AsyncTasks {

    public static Random random = new Random();

    @Async
    public CompletableFuture<Integer> doTaskOne() throws Exception {
        log.info("开始task1");
        long start = System.currentTimeMillis();
        Thread.sleep(5000);
        log.info("task1结束耗时:" + (System.currentTimeMillis() - start) + "毫秒");
        return CompletableFuture.completedFuture(1);
    }

    @Async
    public CompletableFuture<Integer> doTaskTwo() throws Exception {
        log.info("开始task2");
        long start = System.currentTimeMillis();
        Thread.sleep(6000);
        log.info("task2结束耗时:" + (System.currentTimeMillis() - start) + "毫秒");
        return CompletableFuture.completedFuture(2);
    }
}
测试输出:
@Slf4j
@SpringBootTest
public class Chapter75ApplicationTests {

    @Autowired
    private AsyncTasks asyncTasks;

    @Test
    public void test() throws Exception {
        long start = System.currentTimeMillis();
        CompletableFuture<Integer> task1 = asyncTasks.doTaskOne();
        CompletableFuture<Integer> task2 = asyncTasks.doTaskTwo();
        CompletableFuture.allOf(task1, task2).join();
        log.info("总耗时:" + (System.currentTimeMillis() - start) + "毫秒");
    }

}
输出结果:
2021-09-16 00:08:55.073  INFO 22304 --- [         task-2] com.didispace.chapter75.AsyncTasks       : 开始task2
2021-09-16 00:08:55.073  INFO 22304 --- [         task-1] com.didispace.chapter75.AsyncTasks       : 开始task1
2021-09-16 00:09:00.080  INFO 22304 --- [         task-1] com.didispace.chapter75.AsyncTasks       : task1结束耗时:5007毫秒
2021-09-16 00:09:01.086  INFO 22304 --- [         task-2] com.didispace.chapter75.AsyncTasks       : task2结束耗时:6013毫秒
2021-09-16 00:09:01.087  INFO 22304 --- [           main] c.d.chapter75.Chapter75ApplicationTests  : 总耗时:6034毫秒
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值