java新特性--09--CompletableFuture 案例

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档


CompletableFuture 案例

1.主逻辑

@SpringBootTest
@RunWith(SpringRunner.class)
@Slf4j
public class Mytest {

    @Autowired
    AudienceService audienceService;

    public final ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(2,
            4,
            300,
            TimeUnit.SECONDS,
            new ArrayBlockingQueue<>(64),
            Executors.defaultThreadFactory(),
            new ThreadPoolExecutor.CallerRunsPolicy());

    @Test
    public void test1() throws Exception {
        try {
            List<String> tableNames = Arrays.asList("t_audience_0","t_audience_1","t_audience_2","t_audience_3","t_audience_4");
            List<CompletableFuture<Integer>> futures = new ArrayList(tableNames.size());
            long start = System.currentTimeMillis();
            for (String tableName : tableNames) {
                TaskParamWrapper taskParamWrapper = new TaskParamWrapper();
                taskParamWrapper.setTableName(tableName);
                chooseAudienceFileTask(tableName,futures);
            }
            //结束
            CompletableFuture<Void> allCompletableFuture = CompletableFuture.allOf(futures.toArray(new CompletableFuture[futures.size()]));
            List<Integer> taskResult = allCompletableFuture.thenApply(e -> futures.stream().map(CompletableFuture::join).collect(Collectors.toList())).join();
            long end = System.currentTimeMillis();
            Integer count = taskResult.stream().reduce(0, Integer::sum);
            log.info("【{}】表查询总条数【{}】", tableNames, count, (end - start));
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            threadPoolExecutor.shutdown();
            //等待所有线程池的任务完成,最多等待三分钟
            threadPoolExecutor.awaitTermination(3, TimeUnit.MINUTES);
        }
    }


    private void chooseAudienceFileTask(String tableName, List<CompletableFuture<Integer>> futures) {
        CompletableFuture<Integer> future = CompletableFuture.supplyAsync
                (() -> new tbTask(audienceService, tableName).execute(), threadPoolExecutor);
        futures.add(future);
    }

    }
}

2.task任务

 class tbTask {
        private String tableName;
        private AudienceService audienceService;

        public tbTask(AudienceService audienceService ,String tableName) {
            this.audienceService = audienceService;
            this.tableName = tableName;
        }

        public Integer execute() {
            int count=0;
            long start = System.currentTimeMillis();
            AudienceFileBatchParam audienceParam = new AudienceFileBatchParam();
            audienceParam.setTableName(tableName);
            audienceParam.setNums(5);
            //t_audience_*表
            List<AudienceModel> audienceModels = audienceService.selectSingleAudienceTable(audienceParam);
            if(!CollectionUtils.isEmpty(audienceModels)){
                count=audienceModels.size();
            }
            System.out.println("==================================="+tableName+"查询到"+count+"条"+"===================================");
            long end = System.currentTimeMillis();
            log.info("查询【{}】表,总条数【{}】耗时【{}】ms",audienceParam.getTableName(),count,(end-start));
            return count;
        }
    }
}

3.测试

===================================t_audience_1查询到1===================================
2025-01-17 17:22:29.139-21268-[,,]-[pool-1-thread-2] INFO   com.tuzhanai.audience.server.Mytest      [Mytest.java:101] - 查询【t_audience_1】表,总条数【1】耗时【656】ms
===================================t_audience_0查询到5===================================
2025-01-17 17:22:29.154-21268-[,,]-[pool-1-thread-1] INFO   com.tuzhanai.audience.server.Mytest      [Mytest.java:101] - 查询【t_audience_0】表,总条数【5】耗时【671】ms
===================================t_audience_2查询到0===================================
2025-01-17 17:22:29.234-21268-[,,]-[pool-1-thread-2] INFO   com.tuzhanai.audience.server.Mytest      [Mytest.java:101] - 查询【t_audience_2】表,总条数【0】耗时【95】ms
===================================t_audience_3查询到5===================================
2025-01-17 17:22:29.270-21268-[,,]-[pool-1-thread-1] INFO   com.tuzhanai.audience.server.Mytest      [Mytest.java:101] - 查询【t_audience_3】表,总条数【5】耗时【116】ms
===================================t_audience_4查询到5===================================
2025-01-17 17:22:29.338-21268-[,,]-[pool-1-thread-2] INFO   com.tuzhanai.audience.server.Mytest      [Mytest.java:101] - 查询【t_audience_4】表,总条数【5】耗时【104】ms
2025-01-17 17:22:29.342-21268-[,,]-[main] INFO   com.tuzhanai.audience.server.Mytest      [Mytest.java:61] -[t_audience_0, t_audience_1, t_audience_2, t_audience_3, t_audience_4]】表查询总条数【16

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值