在springboot上通过CompletableFuture实现多异步任务合并汇总

@Servicepublic class WorkAsyncService { @Async public CompletableFuture<String> doWork(String value){ System.out.pri...
摘要由CSDN通过智能技术生成
@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);
    
  • 0
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
CompletableFutureJava8中新增的异步编程工具,可以用于实现异步任务的组合。下面是两种常用的组合方式: 1. anyOf方法:任意一个任务执行完,就执行anyOf返回的CompletableFuture。如果执行的任务异常,anyOf的CompletableFuture,执行get方法,会抛出异常。 ```java CompletableFuture<String> future1 = CompletableFuture.supplyAsync(() -> { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } return "Hello"; }); CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> { try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } return "World"; }); CompletableFuture<Object> anyFuture = CompletableFuture.anyOf(future1, future2); System.out.println(anyFuture.get()); // 输出:Hello ``` 2. allOf方法:所有任务都执行完成后,才执行allOf返回的CompletableFuture。如果任意一个任务异常,allOf的CompletableFuture,执行get方法,会抛出异常。 ```java CompletableFuture<String> future1 = CompletableFuture.supplyAsync(() -> { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } return "Hello"; }); CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> { try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } return "World"; }); CompletableFuture<Void> allFuture = CompletableFuture.allOf(future1, future2); allFuture.get(); System.out.println(future1.get() + " " + future2.get()); // 输出:Hello World ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值