之前存在一个请求后端接口的一个程序,之前用串行的方式,这样花费的时间太长,如果这样的太多,就比较费时间。之前犹豫项目的做不完,所以就把这个搁置了,趁着五一没有出行计划,就在家看了看把项目改了改,就把这个记录下来。
很多时候我们都会用到线程池,我们在执行线程的时候,我们都用ExecutorService这个来实现,这样是对线程池的一个包装,这样就减少了开发的难度。就像每一个请求都需要对返回值做处理,我们要采用Callable而不是Runable,需要把返回值接回来,我们采要FutureTask,把我修改完的代码粘贴一下:
ExecutorService executorService=Executors.newFixedThreadPool(10);
List<FutureTask< Map<String,Map<String,Integer>>>> futuress=Lists.newArrayList();
FutureTask< Map<String,Map<String,Integer>>> infoFutureTask=new FutureTask< Map<String,Map<String,Integer>>>(
new Callable< Map<String,Map<String,Integer>>>() {
@Override
public Map<String,Map<String,Integer>> call() throws Exception {
Map<String,Map<String,Integer>> map=Maps.newHashMap();
return map;
}
});
executorService.submit(infoFutureTask);
futuress.add(infoFutureTask );
Thread.sleep(500l);
try {
for (Map.Entry<String, Map<String, Integer>> integerMapEntry : futures.get().entrySet()) {
integerMapEntry.getValue();//获取返回值
}
} catch (ExecutionException e) {
e.printStackTrace();
}finally{
if(!executorService.isShutdown()){
executorService.shutdown();
}
}
一定要记得把线程池关了,否则jdk内存占用太高了。自己遇到过。