按顺序获取多线程的返回值



@Controller("")
@RequestMapping("")
public class Controller
{
	

	private String IMPORT_EXCEL_PAHT;

	private String EXCEL_BASE_PAHT;

	

	@RequestMapping("dzgs_export")
	@ResponseBody
	public String dzgsExportExcel(HttpServletRequest request, HttpServletResponse response) throws IOException
	{
		String result = "";
		String uid = UUID.randomUUID().toString();
		LOG.info("(" + uid + ")dzgs_export" + System.currentTimeMillis());
		try
		{
			

			List<PolicyInfoExportDomain> domainList = new ArrayList<>();
            // 从数据库里查询(假的)
			List<Policy> policyList = service.findList();

			LOG.info("(" + uid + ")policyList准备完毕,admin.username=" + admin.getUsername()
					+ "   policyList.size=" + policyList.size());

			// 开启多线程,按顺序返回组装好的domain
			int length = policyList.size();
			int threadNum = 10;// 最多10个线程
			int tl = length % threadNum == 0 ? length / threadNum : (length / threadNum + 1); //每个线程处理tl条数据
			for (int i = 0; i < threadNum; i++)
			{
				// 分割数据
				int end = (i + 1) * tl;
				end = Math.min(end, length);
				int start = i * tl;
				if(start >= end)
				{
					break;
				}
				// 通过FutureTask使得线程返回的结果按顺序加入domainList
				FutureTask<List<Domain>> f1 = new FutureTask<>(
					new MyCall("线程[" + (i + 1) + "] ", policyList.subList(start, end), admin.getUsername()));
				Thread t1 = new Thread(f1, "线程[" + (i + 1) + "] ");
				t1.start();// 开启线程
				domainList.addAll(f1.get());// 获取每个线程的返回值
			}




		}
		catch (Exception e)
		{
			LOG.error("(" + uid + ")/admin/policy_info_latest/dzgs_export", e);
			
		}
		LOG.info("(" + uid + ")result" + System.currentTimeMillis());
		return result;

	}


	static class MyCall implements Callable<List<Domain>>
	{
		private String threadName;

		private List<Policy> data;

		private String username;

		public MyCall(String threadName, List<Policy> data, String username)
		{
			this.threadName = threadName;
			this.data = data;
			this.username = username;
		}

		@Override
		public List<Domain> call() throws Exception
		{
			List<Domain> domainList = new ArrayList<>();
			LOG.info("开启线程" + threadName + ":" + System.currentTimeMillis());
			for (Policy policy : data)
			{

				// 根据数据库里查到的实体,组装新的实体
				Domain domain = new Domain(policy);
				
				domainList.add(domain);
			}
			LOG.info(threadName + "处理了:" + data.size() + "条!" + System.currentTimeMillis());
			return domainList;
		}
	}

}

通过多线程来节约某些耗时操作的时间,此写法可以获取每个线程的返回值,并按照开启的顺序获取返回值。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值