加載xml文件
在applicationcontext.xml文件里面添加
1
|
xmlns:task= "http://www.springframework.org/schema/task" |
xmlns文件并且xsi:schemalocation中添加
1
|
http: //www.springframework.org/schema/task |
1
|
http: //www.springframework.org/schema/task/spring-task.xsd |
在spring中配置executor
在applicationcontext.xml文件里面添加
1
2
3
4
5
6
7
8
9
10
11
12
|
<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添加
1
2
3
4
|
maxopenpreparedstatements= 20 removeabandoned= true removeabandonedtimeout= 1800 logabandoned= true |
這是分別對線程池做配置
添加依賴注入
在所需要的service或者controller類里面添加
1
2
|
@resource (name = "taskexecutor" ) private taskexecutor taskexecutor; |
使用線程池進行并發操作
代碼如下
1
2
3
4
5
6
7
8
9
10
11
12
|
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中聲明變量如下
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
@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; } |
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,謝謝大家對服務器之家的支持。如果你想了解更多相關內容請查看下面相關鏈接
原文鏈接:https://blog.csdn.net/u014320421/article/details/79295944