springmvc配置线程池Executor做多线程并发操作的代码实例
加载xml文件
在ApplicationContext.xml文件里面添加
xmlns:task="http://www.springframework.org/schema/task"
xmlns文件并且xsi:schemaLocation中添加
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task.xsd
在spring中配置Executor
在ApplicationContext.xml文件里面添加
在dbconfig.properties添加
maxOpenPreparedStatements=20 removeAbandoned=true removeAbandonedTimeout=1800 logAbandoned=true
这是分别对线程池做配置
添加依赖注入
在所需要的service或者controller类里面添加
@Resource(name="taskExecutor") privateTaskExecutortaskExecutor;
使用线程池进行并发操作
代码如下
taskExecutor.execute(newRunnable(){
@Override
publicvoidrun(){
//TODOAuto-generatedmethodstub
try{
//要进行的并发操作
}catch(Exceptione){
//TODOAuto-generatedcatchblock
e.printStackTrace();
}
}
});
提示
注意在线程中操作变量时候变量的作用域范围。需要在这个controller或者sevice中声明变量如下
@Controller
publicclassIndexController{
intstudentscount=0;
@RequestMapping(value="/index.html")
publicModelAndViewgoIndex(){
logBefore(logger,"列表Center");
ModelAndViewmv=this.getModelAndView();
taskExecutor.execute(newRunnable(){
@Override
publicvoidrun(){
//TODOAuto-generatedmethodstub
//得到所有学生人数
try{
studentscount=coursesService.getStudentCount(pd);
}catch(Exceptione){
//TODOAuto-generatedcatchblock
e.printStackTrace();
}
}
});
mv.addObject("studentscount",studentscount);
mv.setViewName("common/index");
returnmv;
}
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对毛票票的支持。如果你想了解更多相关内容请查看下面相关链接