java 多线程两种方案

     long startTime = System.currentTimeMillis();
            System.out.println("开始查询-->");
            List<Callable<HashMap<String, List<SiteBaseInfo>>>> taskList = new ArrayList<>();//创建任务
            DataScope dataScope = new DataScope();
            dataScope.setDeptCode(siteBaseInfo.getDeptCode());
            dataScope.setIsDeptCode(true);
            String deptCode = siteBaseInfo.getDeptCode();
            List<String> strings = BeanValueTrimUtil.changeStringToList(deptCode);
            for (String s : strings) {
                RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
                Callable< HashMap<String, List<SiteBaseInfo>>> task = new Callable<HashMap<String, List<SiteBaseInfo>>>() {
                    @Override
                    public HashMap<String, List<SiteBaseInfo>> call() throws Exception {
                        SiteBaseInfo siteBaseInfo1 = new SiteBaseInfo();
                        siteBaseInfo1.setDeptCode(s);
                        RequestContextHolder.setRequestAttributes(requestAttributes, true);
                        HashMap<String, List<SiteBaseInfo>> stringObjectHashMap = new HashMap<>();
                        try {
                            DataScope dataScope = new DataScope();
                            siteBaseInfo.setDeleteFlag("0");
                            siteBaseInfo.setIsLogicalFlag("0");
                            if (StringUtils.isNotBlank(siteBaseInfo.getDeptCode())) {
                                dataScope.setDeptCode(siteBaseInfo.getDeptCode());
                                siteBaseInfo.setDeptCode(null);
                            } else if (SecurityUtils.getUser() != null) {
                                R treeR = myRemoteDeptService.tree(null, null, null);
                                List<Map<String, Object>> s = (List<Map<String, Object>>) treeR.getData();
                                dataScope.setDeptCode((String) s.get(0).get("id"));
                            }
                            dataScope.setIsDeptCode(true);
                            QueryWrapper<SiteBaseInfo> siteBaseInfoQueryWrapper = new QueryWrapper<>(siteBaseInfo);
                            LambdaQueryWrapper<SiteBaseInfo> lambda = siteBaseInfoQueryWrapper.lambda();
                            lambda.eq(SiteBaseInfo::getDeleteFlag, "0");
                            lambda.eq(SiteBaseInfo::getIsLogicalFlag, "0");
                            if (StringUtils.isNotBlank(siteBaseInfo.getSiteName())) {
                                lambda.like(SiteBaseInfo::getSiteName, siteBaseInfo.getSiteName());
                            }
                            List<SiteBaseInfo> siteBaseInfos = siteBaseInfoMapper.selectSiteBaseInfoListNoPage2(siteBaseInfoQueryWrapper,s);
                            stringObjectHashMap.put(s,siteBaseInfos);
                            return stringObjectHashMap;
                        } catch (Exception e) {
                            e.printStackTrace();
                            log.error("分页查询超时page" + s);
                            return null;
                        }
                    }
                };//条件查询,name没有就给null
                taskList.add(task);
            }
            int threadNum = 10;//可自定义线程数量
            ExecutorService executor = Executors.newFixedThreadPool(threadNum);
            List<Future<HashMap<String, List<SiteBaseInfo>>>> futureList = executor.invokeAll(taskList);
            if (futureList != null && futureList.size() > 0) {
                for (Future<HashMap<String, List<SiteBaseInfo>>> future : futureList) {
                    if (future.get() != null) {
//                        list.addAll(future.get());
                        HashMap<String, List<SiteBaseInfo>> stringListHashMap = future.get();
                        returnMap.putAll(stringListHashMap);
                    }
                }
            }
            executor.shutdown();//关闭线程
            long endTime = System.currentTimeMillis();
            long s = ((endTime - startTime) / 1000);
            System.out.println(threadNum + "个线程查询花了" + s + "秒");
        } catch (Exception e) {
            log.error("siteBaseInfoPage{}", e);
        }
        return R.ok(returnMap);

第二种

  try {
            List<FutureTask<Map<String, Object>>> resultList = new ArrayList<>();
            for (SysDept d : subDeptList) {
                FutureTask<Map<String, Object>> futureTask = new FutureTask<>(new myTask(baseMapper, d));
                executorService.submit(futureTask);
                //future异步模式,把任务放进去先,先不取结果
                resultList.add(futureTask);
            }
            resultList.forEach(e -> {
                try {
                    result.add(e.get());
                } catch (InterruptedException | ExecutionException ex) {
                    throw new RuntimeException(ex);
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
            executorService.shutdown();
            return R.ok();
        }
        executorService.shutdown();
        return R.ok(result);
@Slf4j
class myTask implements Callable<Map<String, Object>> {

    private final SiteBaseInfoMapper mapper;

    private final SysDept dept;

    public myTask(SiteBaseInfoMapper mapper, SysDept dept) {
        this.mapper = mapper;
        this.dept = dept;
    }

    @Override
    public Map<String, Object> call() throws Exception {
        long s = System.currentTimeMillis();
        log.info("====================" + dept.getName() + "开始=====================================");
        //查询组织机构下级所有组织机构编码
        long t = System.currentTimeMillis();
//            List<KeyDevBaseInfoDto> keyDevBaseInfoDtoList = mapper.getDevSummaryByDevClassOfALevelByCodes(dept.getDeptCode());
        List<Map> keyDevBaseInfoDtoList = mapper.getSiteBaseInfoStatisticsByBusinessTypeCodes2(dept.getDeptCode(),"true");
        List<Map> aFalse = mapper.getSiteBaseInfoStatisticsByBusinessTypeCodes2(dept.getDeptCode(), "false");
        keyDevBaseInfoDtoList.addAll(aFalse);
        long ed = System.currentTimeMillis();
        log.info("======================" + dept.getName() + "查询数据库耗时:" + (ed - t) / 1000);
        Map<String, Object> dtoMap = new HashMap<>();
        dtoMap.put("111", 0);
        dtoMap.put("222", 0);
        dtoMap.put("333", 0);
        dtoMap.put("444", 0);
        dtoMap.put("555", 0);
        dtoMap.put("666", 0);
        for (Map map : keyDevBaseInfoDtoList) {
            String dtoMapKey = (String) map.get("business_type_codes") +map.get("site_type") ;
            dtoMap.put(dtoMapKey, (Long) map.get("quantity"));
        }
        dtoMap.put("deptName", ObjectUtil.isNotEmpty(dept.getShortName()) ? dept.getShortName() : dept.getName());

        List<String> sortList = Arrays.asList("1", "2", "3", "4", "5","6");
        Map sortedMap = dtoMap.entrySet().stream()
                .sorted(Comparator.comparing(entry -> sortList.indexOf(entry.getKey())))
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
                        (oldValue, newValue) -> oldValue, LinkedHashMap::new));
        long o = System.currentTimeMillis();
        log.info("=========================" + dept.getName() + "总耗时:" + (o - s) / 1000);
        return sortedMap;
    }
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值