下面是我写的自定义线程
private class ReportThread implements Callable<List<ReportV>> {
public String time;
public String tableCode;
public String company;
public String insertTime;
public Map<String, String> columnName1;
public Map<String, String> columnName2;
public List<Map<String, String>> columnMapList;
public List<ReportV> reportVs;
@Override
public List<ReportV> call() throws Exception {
try {
if (Objects.isNull(columnName2)) {
reportVs= dataController.selectData(tableCode, columnName1, time, company, insertTime);
} else {
reportVs= dataController.selectData(tableCode, columnName1, time, company, insertTime);
reportVs.addAll(dataController.selectData(tableCode, columnName2, time, company, insertTime));
}
} catch (Exception e) {
e.printStackTrace();
}
return reportVs;
}
}
调用自定义线程的代码
private List<ReportV> executor() throws Exception {
ExecutorService executorService = Executors.newFixedThreadPool(10);
// ExecutorService executorService = Executors.newCachedThreadPool();
List<Callable<List<ReportV>>> tasks = new ArrayList<>();
//和future的返回值保持一致,才能正常取回
if (!quarterFlag) {
ReportThread reportThread1 = new ReportThread();
reportThread1.setTableCode("xxx");
tasks.add(reportThread1);
//executorService.submit(reportThread1);
ReportThread reportThread2 = new ReportThread();
reportThread2.setTableCode("ooo");
tasks.add(reportThread2);
} else {
ReportThread reportThreadQuarter = new ReportThread();
reportThreadQuarter.setTableCode("kkk");
tasks.add(nccReportThreadQuarter);
}
List<Future<List<ReportV>>> futures = executorService.invokeAll(tasks);
executorService.shutdown();//停止接收新任务
// shutdownNow():停止接收新任务,原来的任务停止执行
while (!executorService.isTerminated()) {
}
List<ReportV> reportVS = new ArrayList<>();
futures.forEach(item -> {
try {
reportVS.addAll(item.get());
} catch (Exception e) {
e.printStackTrace();
}
});
log.info("###reportVS= {}", reportVS);
return reportVS;
}
获取线程的返回值,这里使用的是future.get()这个方法。但是返回值类型需要在自定义线程的实施类后面定义,如下:
ReportThread implements Callable<List<ReportV>//Callable<T>
随后是定义Callable的类型:
List<Callable<List<ReportV>>> tasks = new ArrayList<>();
//和future的返回值保持一致,才能正常取回
这样之后调用future.get()的时候才能够取到ReportV这个对象的List。
如有不对,请多指教。