加载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文件里面添加
<bean id="taskExecutor" class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor">在dbconfig.properties添加
<!-- 核心线程数 -->
<property name="corePoolSize" value="${task.core_pool_size}" />
<!-- 最大线程数 -->
<property name="maxPoolSize" value="${task.max_pool_size}" />
<!-- 队列最大长度 -->
<property name="queueCapacity" value="${task.queue_capacity}" />
<!-- 线程池维护线程所允许的空闲时间,默认为60s -->
<property name="keepAliveSeconds" value="${task.keep_alive_seconds}" />
</bean>
<!-- 注解式 -->
<task:annotation-driven />
maxOpenPreparedStatements=20removeAbandoned=trueremoveAbandonedTimeout=1800logAbandoned=true这是分别对线程池做配置
添加依赖注入
在所需要的service或者controller类里面添加
@Resource(name = "taskExecutor")
private TaskExecutor taskExecutor;
使用线程池进行并发操作
代码如下
taskExecutor.execute(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
try {
<span style="white-space:pre"> </span>//要进行的并发操作
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
提示
注意在线程中操作变量时候变量的作用域范围。需要在这个controller或者sevice中声明变量如下
@Controller
public class IndexController {
int studentscount = 0;
@RequestMapping(value = "/index.html")
public ModelAndView goIndex() {
logBefore(logger, "列表Center");
ModelAndView mv = this.getModelAndView();
<span style="white-space:pre"> </span>taskExecutor.execute(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
// 得到所有学生人数
try {
studentscount = coursesService.getStudentCount(pd);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
<span style="white-space:pre"> </span>mv.addObject("studentscount", studentscount);
<span style="white-space:pre"> </span>mv.setViewName("common/index");
<span style="white-space:pre"> </span>return mv;
}