优化一个系统中的功能,需要通过判断进行多次的查库,查库的性能是单表,条件有索引.
public Map<String, String> getTopics(@RequestParam("classroomIds") List<String> classroomIds) {
Map<String, String> map = new HashMap<>();
ExecutorService exec = Executors.newCachedThreadPool();
List<FutureTask<Map<String, String>>> taskList = new ArrayList<FutureTask<Map<String, String>>>();
int n = classroomIds.size()/100;
for (int i = 0 ;i <=n; i++) {
List<String> newclassroomIds1;
if(i==n){
newclassroomIds1 = classroomIds.subList(i*100,classroomIds.size());
}else{
newclassroomIds1 = classroomIds.subList(i*100,(i+1)*100);
}
if(newclassroomIds1!=null && newclassroomIds1.size()>0){
// 传入Callable对象创建FutureTask对象
FutureTask<Map<String, String>> ft=new FutureTask<> ( new Callable<Map<String, String>>() {
public Map<String, String> call() throws DaoException {
Map<String, String> map = new HashMap<>();
for (String classroomId : newclassroomIds1) {
String topic = coursewareConfigService.getConfigOfTopicByClassroomId(classroomId);
map.put(classroomId, topic);
}
return map;
}});
taskList.add(ft);
exec.submit(ft);
}
}
Map<String, String> totalMap = new HashMap<>();
for (FutureTask<Map<String, String>> ft : taskList) {
try {
//FutureTask的get方法会自动阻塞,直到获取计算结果为止
totalMap.putAll(ft.get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
// 关闭线程池
exec.shutdown();
log.info("多任务计算后的总结果是:" + JSON.toJSONString(totalMap));
return totalMap;