记一次用Executors和Callable多线程查询

线程类

public class ThredQuery implements Callable<List<StoreCompDetailEntity>> {

    private StoreBrokenCompMapper storeBrokenCompMapper;

    // 查询条件
    private String dateStr;

    // 分页
    private int pageNum;

    private Integer pageSize;

    public ThredQuery(String dateStr, Integer pageNum, Integer pageSize, StoreBrokenCompMapper storeBrokenCompMapper){
        this.dateStr = dateStr;
        this.pageNum = pageNum + 1;
        this.pageSize = pageSize;
        this.storeBrokenCompMapper = storeBrokenCompMapper;
    }

    @Override
    public List<StoreCompDetailEntity> call() throws Exception {
        Map<String, Object> map = new HashMap<String, Object>(3);
        map.put("dateStr", dateStr);
        map.put("pageNum", pageNum);
        map.put("pageSize", pageSize);
        List<StoreCompDetailEntity> result = storeBrokenCompMapper.getStoreCompDetails(map);
        return result;
    }
}

业务类代码

Map<String, Object> map = new HashMap<String, Object>();
        map.put("dateStr", dateStr);
        ArrayList<StoreCompDetailEntity> entities = new ArrayList<StoreCompDetailEntity>();
        int nums = 50; //每次查询的条数
        int count = storeBrokenCompMapper.selectStoreCompDetailsCount(map); // 总行数
        int pageCount = (count % nums == 0) ? (count / nums) : (count / nums + 1);// 多少页
        List<Callable<List<StoreCompDetailEntity>>> tasks = new ArrayList<Callable<List<StoreCompDetailEntity>>>();
        for (int i = 0; i < pageCount; i++) {
            Callable<List<StoreCompDetailEntity>> qfe = new ThredQuery(dateStr,i,nums,storeBrokenCompMapper);
            tasks.add(qfe);
        }
        //定义固定长度的线程池  防止线程过多
        ExecutorService executorService = Executors.newFixedThreadPool(15);
        //Future用于获取结果
        List<Future<List<StoreCompDetailEntity>>> futures=executorService.invokeAll(tasks);
        //处理线程返回结果
        if(futures!=null&&futures.size()>0){
            for (Future<List<StoreCompDetailEntity>> future:futures){
                entities.addAll(future.get());
            }
        }
        for(StoreCompDetailEntity entity : entities){
            if(StringUtil.isNotEmpty(entity.getCreateTime()) && entity.getCreateTime().length() > 19){
                entity.setCreateTime(entity.getCreateTime().substring(0,19));
            }
        }
        // 关闭线程池
        executorService.shutdown();
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值