CompletableFuture的thenCombine结果组合用法实例

发布时间:2024年01月17日

CompletableFuture的thenCombine结果组合用法实例

thenCombine 方法,合并两个线程任务的结果,并进一步处理。有种大数的MapReduce的思想。
在这里插入图片描述

实例:

    @Autowired
    @Qualifier(ThreadPoolConfig.IMPORT_EXECUTOR)
    private ThreadPoolTaskExecutor threadPoolTaskExecutor;
public List<Object> queryRecentOrders(String custNo) {
        CompletableFuture<List<Integer>> future1 = CompletableFuture
                .supplyAsync(() -> {
                    int number = 1;
                    List<Integer> integers = Lists.newArrayList(number);
                    System.out.println("first:" + integers);
                    return integers;
                }, threadPoolTaskExecutor);

        CompletableFuture<List<Integer>> future2 = CompletableFuture
                .supplyAsync(new Supplier<List<Integer>>() {
                    @Override
                    public List<Integer> get() {
                        int number = 2;
                        List<Integer> integers = Lists.newArrayList(number);
                        System.out.println("second:" + integers);
                        return integers;
                    }
                }, threadPoolTaskExecutor);

        CompletableFuture<List<Integer>> future3 = CompletableFuture
                .supplyAsync(new Supplier<List<Integer>>() {
                    @Override
                    public List<Integer> get() {
                        int number = 3;
                        List<Integer> integers = Lists.newArrayList(number);
                        System.out.println("third:" + integers);
                        return integers;
                    }
                }, threadPoolTaskExecutor);

        CompletableFuture<Integer> result = future1
                .thenCombine(future2, (x, y) -> {
                    System.err.println("x:" + x);
                    System.err.println("y:" + y);
                    Integer sum = Lists.newArrayList(x, y).stream().flatMap(k -> k.stream()).reduce(0, Integer::sum);
                    return sum;
                }).thenCombine(future3, (x, y) -> {
                    System.err.println("x:" + x);
                    System.err.println("y:" + y);
                    y.add(x);
                    Integer reduce = y.stream().reduce(0, Integer::sum);
                    return reduce;
                });

        try {
            Integer integer = result.get();
            System.err.println(integer+"-----------------");
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }

        return null;

    }

总结

  1. thenCombine 用法,是将任务用多线程分组执行再组合。在项目实战中应用场景还是比较多的。
  2. 项目实例写得还不够优雅,还有优化空间
文章来源:https://blog.csdn.net/wayne_youlu/article/details/135657291
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。