@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;
}
}
}
通过多线程来节约某些耗时操作的时间,此写法可以获取每个线程的返回值,并按照开启的顺序获取返回值。