springmvc配置線程池Executor做多線程并發(fā)操作的代碼實例
加載xml文件
在ApplicationContext.xml文件里面添加
xmlns:task="http://www.springframework.org/schema/task"
xmlns文件并且xsi:schemaLocation中添加
在spring中配置Executor
在ApplicationContext.xml文件里面添加
<bean id="taskExecutor" class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor"> <!-- 核心線程數(shù) --> <property name="corePoolSize" value="${task.core_pool_size}" /> <!-- 最大線程數(shù) --> <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;
使用線程池進行并發(fā)操作
代碼如下
taskExecutor.execute(new Runnable() { @Override public void run() { // TODO Auto-generated method stub try { //要進行的并發(fā)操作 } 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 // 得到所有學生人數(shù) 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; }
總結(jié)
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學習或者工作具有一定的參考學習價值,謝謝大家對腳本之家的支持。如果你想了解更多相關內(nèi)容請查看下面相關鏈接
相關文章
mybatis中如何實現(xiàn)一個標簽執(zhí)行多個sql語句
這篇文章主要介紹了mybatis中如何實現(xiàn)一個標簽執(zhí)行多個sql語句問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-04-04JAVA發(fā)送http get/post請求,調(diào)用http接口、方法詳解
這篇文章主要介紹了Java發(fā)送http get/post請求調(diào)用接口/方法,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2019-04-04java開發(fā)中使用IDEA活動模板快速增加注釋的方法
這篇文章主要介紹了java開發(fā)中使用IDEA活動模板快速增加注釋,本文通過圖文并茂的形式給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-12-12