线程池实现for循环优化(支持返回值的线程池Callable)

项目中设计到,查询近12个月的数据成长轨迹,本想着直接通过数据库中查询得到,但实际的业务场景中涉及到关联表和统计查询等,使用时间匹配后无法使用时间索引进行优化查询等原因放弃数据库优化策略。后参考网上优化建议,在Java中for循环中采用线程的方式进行速度优化。暂时查询速度是有所提高,只是不太后期会不会因为线程问题导致别的未知问题。暂时记录本次优化过程。

因正常的线程方式Thread、Runnable方式因不能获取返回值,所以采用callable实现该功能。

1、创建对应的线程类实现Callable接口

class CallableThread implements Callable<Map<String, Object>> {
    int i;
    int total;
    String orgId;
    String userId;
    String queryType;
    String quarter;
    private CustomerMarketingService marketingService;
    private Map<String, Object> map = new HashMap<>();
    private final CountDownLatch latch ;

    public CallableThread(int i,int total, String orgId,String userId,
                          String queryType,String quarter,
                          CustomerMarketingService marketingService, CountDownLatch latch) {
        this.i = i;
        this.total = total;
        this.orgId = orgId;
        this.userId = userId;
        this.queryType = queryType;
        this.quarter = quarter;
        this.marketingService = marketingService;
        this.latch = latch;
    }

    @Override
    public Map<String, Object> call() throws Exception {
        try{
            String time="";
            String resultTime="";
            if("day".equals(queryType)){
                time = DateUtils.getDay(i-total+1);
                resultTime=time.substring(5,time.length());
            }
            else if ("month".equals(queryType)) {
                time = DateUtils.getLastMonth(total-i-1, new Date());
                resultTime=time;
            } else if ("quarter".equals(queryType)) {
                time = DateUtils.getLastMonth((total-i-1) * 3, new Date());
                quarter = DateUtils.getSeason(time);
                String year = DateUtils.getYear(time);
                resultTime = year + "年" + quarter + "季度";

            }else if ("year".equals(queryType)) {
                time = DateUtils.getLastMonth((total-i-1) * 12, new Date());
                String year = DateUtils.getYear(time);
                resultTime = year + "年";
            }


            //客户营销统计-(新客户/总数+具体客户营销方式统计)
            int newCount =0;
            int allCount =0;
            //EntityWrapper<CustomerMarketingEntity> ew = new EntityWrapper<>();
            Map<String,Object> params = new HashMap<>();
            if("day".equals(queryType)){
                //ew.between("create_time", time+" 00:00:00",time+" 23:59:59");
                params.put("beginTime",time+" 00:00:00");
                params.put("endTime",time+" 23:59:59");
            }else{
                Date beginTime = DateUtils.getBeginTime(queryType, time, quarter);
                Date endTime = DateUtils.getEndTime(queryType, time, quarter);
                params.put("beginTime",DateUtils.format(beginTime)+" 00:00:00");
                params.put("endTime",DateUtils.format(endTime)+" 23:59:59");
                //ew.between("create_time", DateUtils.format(beginTime)+" 00:00:00",DateUtils.format(endTime)+" 23:59:59");
            }


            if (UtilValidate.isNotEmpty(orgId)) {
                //拼接权限的查询条件
                params.put("orgId",orgId);
                //ew.addFilter("FIND_IN_SET(create_org_id,getChildrenOrg({0}))", orgId);
            }
            List<CustomerMarketCount> list = marketingService.selectCountAONList(params);
            for(CustomerMarketCount count:list){
                if("0".equals(count.getCode())){
                    newCount=count.getCount();
                }
                allCount=allCount+count.getCount();
            }
            //allCount = marketingService.selectCountM(params);
            //params.put("isNew","0");
            //ew.eq("is_new", "0");
            //newCount = marketingService.selectCountM(params);
            // 新客户
            map.put("resultTime", resultTime);
            map.put("time", resultTime);
            map.put("allCount", allCount);
            map.put("newCount", newCount);
            double ratio;
            if(allCount!=0){
                ratio=(double)newCount/allCount;
                map.put("ratio", CountUtil.formatDouble(ratio));
            }else{
                map.put("ratio", 0.0);
            }
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            latch.countDown();
        }
        return map;
    }
}

2、具体的业务逻辑中,通过线程池调用该线程

        List<Map<String, Object>> mapList = new ArrayList<>();        
        final CountDownLatch latch = new CountDownLatch(total);
        ExecutorService pool=Executors.newFixedThreadPool(5);
        List list=new ArrayList();
        try {
            for (int i = 0; i < total; i++) {//生长轨迹
                Callable<Map<String, Object>> c1 = new CallableThread(i,total,orgId,userId,queryType,quarter,this,latch);
                Future<Map<String,Object>> f1=pool.submit(c1);
                list.add(f1);
            }
            latch.await(); //等待所有线程执行完成后 对返回值进行合并处理
            for(Object o:list){
                Future<Map<String,Object>> f1=(Future<Map<String, Object>>) o;
                mapList.add(f1.get());
            }
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
            return Result.error("未知异常");
        }

通过线程池调用对应的线程,具体某个线程通过传值后处理单独的业务逻辑后,latch.await()等待所有的线程执行完成后,针对返回值进行数据合并后返回给前台。

  • 6
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,以下是用Java编写一个线程池执行Callable类的示例代码: ``` import java.util.concurrent.Callable; public class MyCallable implements Callable<Integer> { private int num; public MyCallable(int num) { this.num = num; } public Integer call() throws Exception { int sum = 0; for (int i = 1; i <= num; i++) { sum += i; } return sum; } } ``` 在这个示例代码中,我们定义了一个名为MyCallable的类,它实现JavaCallable接口,并使用一个整数类型的构造函数来初始化类中的成员变量num。 在call()方法中,我们使用for循环计算从1到num之间的所有整数的和,并将结果作为整数类型的返回值。 当我们在使用线程池执行此Callable类时,将会返回计算结果。例如: ``` import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; public class Main { public static void main(String[] args) throws Exception { ExecutorService executorService = Executors.newFixedThreadPool(2); Future<Integer> result1 = executorService.submit(new MyCallable(5)); Future<Integer> result2 = executorService.submit(new MyCallable(10)); System.out.println("Result1 = " + result1.get()); System.out.println("Result2 = " + result2.get()); executorService.shutdown(); } } ``` 在这个示例代码中,我们首先创建了一个固定大小为2的线程池(可根据实际情况自行调整),然后分别用参数5和10创建了两个MyCallable类的实例,并将它们提交到线程池中执行。 我们还使用Future接口获取了MyCallable类的执行结果,并将结果打印到控制台上。 最后,我们调用线程池的shutdown()方法终止所有线程的执行。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值