Java 实现异步

1、CompletableFuture无返回值

        List> taskList = new ArrayList<>();
        ThreadPoolExecutor executor = ThreadUtils.newThreadPoolExecutors();
        dataList.forEach(dtoList ->
                taskList.add(CompletableFuture.runAsync(() -> doMoth(), executor)));
        CompletableFuture[] completableFutures = taskList.toArray(new CompletableFuture[0]);
        CompletableFuture.allOf(completableFutures).get();
        executor.shutdown();

2、有返回值

        //1)构建一个空的结果集对象
        IndexBaseInfoVO result = new IndexBaseInfoVO();
        //2 封装结果集属性
        // 2.1 由于查询需要用到用户名 调用工具类获取用户名
        String username = SecurityUtils.getUsername();
        try {
            CompletableFuture clueNums = CompletableFuture.supplyAsync(()->{
                // 2.2 开始查询第一个属性 线索数量
                return reportMpper.getCluesNum(beginCreateTime, endCreateTime, username);
            });
            CompletableFuture bussinessNum = CompletableFuture.supplyAsync(()->{
                // 2.3 开始查询第一个属性 商机数量
                return reportMpper.getBusinessNum(beginCreateTime, endCreateTime, username);
            });

            CompletableFuture contractNum = CompletableFuture.supplyAsync(()->{
                // 2.4 开始查询第一个属性 合同数量
                return reportMpper.getContractNum(beginCreateTime, endCreateTime, username);
            });
            CompletableFuture saleAmount = CompletableFuture.supplyAsync(()->{
                // 2.5 开始查询第一个属性 销售金额数量
                return reportMpper.getSalesAmount(beginCreateTime, endCreateTime, username);
            });
            //3 join等待所有线程全部执行完成
            CompletableFuture
                    .allOf(clueNums,
                            bussinessNum,
                            contractNum,
                            saleAmount)
                    .join();
            //4 封装结果集对象
            result.setCluesNum(clueNums.get());
            result.setBusinessNum(bussinessNum.get());
            result.setContractNum(contractNum.get());
            result.setSalesAmount(saleAmount.get());
        }catch (Exception e) {
            e.printStackTrace();
            return null;
        }

你可能感兴趣的:(java,开发语言)