List<Map<String, Object>> list = Lists.newArrayList();
// 生产数据量过多、速度较慢,启用多线程
if (CollectionUtils.isNotEmpty(list)) {
int threadSize = 4;
// 总数据条数
int dataSize = list.size();
// 线程数
int threadNum = dataSize / threadSize;
if (threadNum == 0) threadNum = 1;
// 获取cpu核数
int cpu = Runtime.getRuntime().availableProcessors();
// 线程数
threadNum = cpu > threadNum ? threadNum : cpu;
// 确定任务
threadSize = dataSize / threadNum;
// 定义标记、过滤一下threadNum为整数的情况
// boolean special = dataSize % threadSize == 0;
// 创建线程池
ExecutorService exec = Executors.newFixedThreadPool(threadNum);
// 定义一个任务集合
List<Callable<Integer>> tasks = new ArrayList<>();
Callable<Integer> task = null;
// 每一个任务的数据
List<Map<String, Object>> deliverList = null;
// 确定每条线程的数据
for (int i = 0; i < (dataSize / threadSize); i++) {
if (i == dataSize / threadSize - 1) {
/*if (special) {
break;
}*/
deliverList = list.subList(threadSize * i, dataSize);
} else {
deliverList = list.subList(threadSize * i, threadSize * (i + 1));
}
final List<Map<String, Object>> listStr = deliverList;
task = new Callable<Integer>() {
@SuppressWarnings("unchecked")
@Override
public Integer call() throws Exception {
for (Map<String, Object> taskMap : listStr) {
// 具体业务代码
}
return 1;
}
};
// 这里提交的任务容器列表和返回的Future列表存在顺序对应的关系
tasks.add(task);
}
// 异常处理
List<Future<Integer>> results;
try {
results = exec.invokeAll(tasks);
for (Future<Integer> future : results) {
logger.info("future.get()【】" + future.get());
}
} catch (Exception e) {
e.printStackTrace();
logger.error(e.getMessage());
}
}
多线程
最新推荐文章于 2022-10-30 16:00:07 发布