spring框架管理线程池

xiaoxiao2021-02-27  401

今天来记录一下,如何通过 spring框架 简单配置并管理 线程池

1、首先需要搭建好一个简单的spring框架(当然知道是屁话)

如果不知道怎么搭建spring框架的同学可以看我的上一篇文章,也有可能是上上一篇文章(总之自己找吧)。

2、在applicationContext.xml中配置线程池,如下图:

代码需要码在beans标签内,代码如下:

<!-- 异步线程池 --> <bean id="threadPool" class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor"> <!-- 核心线程数 --> <property name="corePoolSize" value="2"> <!-- 最大线程数 --> <property name="maxPoolSize" value="3"> <!-- 队列最大长度 >=mainExecutor.maxSize --> <property name="queueCapacity" value="10"> <!-- 线程池维护线程所允许的空闲时间 --> <property name="keepAliveSeconds" value="300"> <!-- 线程池对拒绝任务(无线程可用)的处理策略 --> <property name="rejectedExecutionHandler"> <bean class="java.util.concurrent.ThreadPoolExecutor$CallerRunsPolicy"> </bean></property> </property></property></property></property></bean> <bean id="taskUtil" class="spring.taskutil.ThreadTask"> <!-- <constructor-arg ref="taskExecutor" /> --> <property name="taskExecutor" ref="threadPool"> </property></bean>

3、新建上述代码中的 spring.taskutil.ThreadTask类(包名+类型的形式),如下图:

图中代码如下:

private TaskExecutor taskExecutor; public TaskExecutor getTaskExecutor() { return taskExecutor; } public void setTaskExecutor(TaskExecutor taskExecutor) { this.taskExecutor = taskExecutor; } public void printMessages(Runnable r,int i) { taskExecutor.execute(r); System.out.println("add Thread:"+i); }

4、新建启动的线程类:

图中代码如下:

private String message; public MyThread() { } public MyThread(String message) { this.message = message; } public void run() { try { Thread.sleep(5000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println(message); }

5、新建测试类:

这里面的代码就不给大家了,代码码完后,run as--> java application 就可以看到结果了

如果又不对的地方,还请大神及时指出,以免误人子弟

转载请注明原文地址: https://www.6miu.com/read-4805.html

最新回复(0)