多线程实现大批量数据查询

优化一个系统中的功能,需要通过判断进行多次的查库,查库的性能是单表,条件有索引.

public Map<String, String> getTopics(@RequestParam("classroomIds") List<String> classroomIds) {
        Map<String, String> map = new HashMap<>();
          ExecutorService exec = Executors.newCachedThreadPool();
          List<FutureTask<Map<String, String>>> taskList = new ArrayList<FutureTask<Map<String, String>>>();
          int n = classroomIds.size()/100;
          for (int i = 0 ;i <=n; i++) {
                List<String> newclassroomIds1;
                if(i==n){
                      newclassroomIds1 = classroomIds.subList(i*100,classroomIds.size());
                }else{
                      newclassroomIds1 = classroomIds.subList(i*100,(i+1)*100);
                }
                if(newclassroomIds1!=null && newclassroomIds1.size()>0){
                      // 传入Callable对象创建FutureTask对象
                      FutureTask<Map<String, String>> ft=new FutureTask<> ( new Callable<Map<String, String>>() {
                            public Map<String, String> call() throws DaoException {
                                  Map<String, String> map = new HashMap<>();
                                  for (String classroomId : newclassroomIds1) {
                                        String topic = coursewareConfigService.getConfigOfTopicByClassroomId(classroomId);
                                        map.put(classroomId, topic);
                                  }
                                  return map;
                            }});
                      taskList.add(ft);
                      exec.submit(ft);
                }
          }
          Map<String, String> totalMap = new HashMap<>();

          for (FutureTask<Map<String, String>> ft : taskList) {
                try {
                      //FutureTask的get方法会自动阻塞,直到获取计算结果为止
                      totalMap.putAll(ft.get());
                } catch (InterruptedException e) {
                      e.printStackTrace();
                } catch (ExecutionException e) {
                      e.printStackTrace();
                }
          }
          // 关闭线程池
          exec.shutdown();
          log.info("多任务计算后的总结果是:" + JSON.toJSONString(totalMap));
        return totalMap;
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值