多线程

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());
	}
}
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值