多线程Future处理list数据

/**
     * 多线程处理list数据
     */
    public Map execuleThread() {
        Map ret = new LinkedHashMap<>();
        try {
            Long t1 = System.currentTimeMillis();
            List behospitalInfoList = new ArrayList<>(); // 需要处理的列表数据
            int threadNum = 4; // 推荐的总线程数 = cpu个数 * 每个cpu的核数
            List> threadData = divideByCopies(behospitalInfoList, threadNum);
            List> list = new ArrayList<>();

            ExecutorService executor = Executors.newFixedThreadPool(threadNum);
            for (int i = 0; i < threadNum; i++) {
                final int index = i; // 这一行代码很重要,如果使用成员变量,下面会报错
                Future future = executor.submit(new Callable() {
                    @Override
                    public String call() {
                        StringBuffer sb = new StringBuffer();
                        int sucNum = 0, errNum = 0;
                        List data = threadData.get(index);
                        System.out.println("******************************线程" + index + "正在执行");
                        if (ListUtil.isNotEmpty(data)) {
                            for (BehospitalInfo bean : data) {
                                // 处理业务数据
                                if (处理成功) {
                                    sucNum++;
                                } else {
                                    errNum++;
                                }
                            }
                            sb.append("线程" + index + "执行完毕:共【" + data.size() + "】条,成功【" + sucNum + "】条,失败【" + errNum + "】条。");
                        } else {
                            sb.append("线程" + index + "未执行数据");
                        }
                        return sb.toString();
                    }
                });
                list.add(future);
            }

            // 拼接返回数据
            for (int i = 0; i < list.size(); i++) {
                Future future = list.get(i);
                while(!future.isDone()); // 这一行代码很重要
                ret.put("线程" + i , future.get());
            }
            Long t2 = System.currentTimeMillis();
            ret.put("总条数", behospitalInfoList.size());
            ret.put("共执行时间:", (t2 - t1) / 1000 + "秒");
        } catch (Exception e) {
            throw new CommonException(CommonErrorCode.SERVER_IS_ERROR);
        }
        return  ret;
    }

    /**
     * 将列表按列表总长度划分
     *
     * @param originList 数据
     * @param num 份数
     * @param 
     * @return
     */
    public  List> divideByCopies(List originList, int num) {
        List> list = new ArrayList<>();
        if (ListUtil.isEmpty(originList) || num < 0) {
            return null;
        }
        for (int i = 0; i < num; i++) {
            list.add(new ArrayList());
        }
        for (int i = 0; i < originList.size(); i++) {
            list.get(i % num).add(originList.get(i));
        }

        return list;
    }

你可能感兴趣的:(多线程,future)