@Service
public class WorkAsyncService {
@Async
public CompletableFuture<String> doWork(String value){
System.out.println("--------start work------" + Thread.currentThread().getName());
try {
Thread.sleep(4000);
}catch (Exception e){
e.printStackTrace();
}
System.out.println("-------end work----------");
return CompletableFuture.completedFuture(value);
}
}
@RunWith(SpringRunner.class)
@SpringBootTest(classes = DemoApplication.class)
public class DemoApplicationTests {
@Autowired
private WorkAsyncService workAsyncService;
@Test
public void asyncTest() throws Exception {
List<CompletableFuture> cfList = Stream.of("h1", "h2", "h3", "h4").map(v -> {
return workAsyncService.doWork(v);
}).collect(Collectors.toList());
StringBuilder sb = new StringBuilder()
在springboot上通过CompletableFuture实现多异步任务合并汇总
最新推荐文章于 2025-11-05 17:52:59 发布
本文介绍了如何在SpringBoot应用中利用@Async注解实现异步任务,并结合CompletableFuture.allOf方法在所有任务执行完毕后进行结果汇总。同时,提到了在启动类中启用异步支持和配置自定义线程池的关键步骤。

最低0.47元/天 解锁文章
2978

被折叠的 条评论
为什么被折叠?



