springmvc配置线程池Executor做多线程并发操作的代码实例

2025-05-29 0 59

加载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;

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对快网idc的支持。如果你想了解更多相关内容请查看下面相关链接

原文链接:https://blog.csdn.net/u014320421/article/details/79295944

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 springmvc配置线程池Executor做多线程并发操作的代码实例 https://www.kuaiidc.com/109724.html

相关文章

发表评论
暂无评论