加載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"> <!-- 核心線程數 --> <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 />
在dbconfig.properties添加
maxOpenPreparedStatements=20 removeAbandoned=true removeAbandonedTimeout=1800 logAbandoned=true
這是分別對線程池做配置
添加依賴注入
在所需要的service或者controller類里面添加
@Resource(name = "taskExecutor") private TaskExecutor taskExecutor;
使用線程池進行并發操作
代碼如下
taskExecutor.execute(new Runnable() { @Override public void run() { // TODO Auto-generated method stub try { //要進行的并發操作 } 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(); 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(); } } }); mv.addObject("studentscount", studentscount); mv.setViewName("common/index"); return mv; }
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,謝謝大家對VeVb武林網的支持。
|
新聞熱點
疑難解答
圖片精選