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毫秒