Spring线程池

来源:互联网 发布:网上兼职淘宝客服招聘 编辑:程序博客网 时间:2024/05/21 12:50
最近研究了一下spring线程池技术。
起因就是看到同事遇到了并发相关的问题,所以跟着一起折腾这个问题。
下面是对于Spring线程池的研究记录

废话不说,直接上代码

在Spring中配置线程池

<!-- 配置线程池 -->  <bean id ="threadPoolExecutor"  class ="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor" >      <!-- 线程池同时执行的线程数-->  <property name ="corePoolSize" value ="10" />      <!-- 线程池维护线程所允许的空闲时间(超过corePoolSize数量的线程,不被销毁,保持其状态的时间) -->  <property name ="keepAliveSeconds" value ="30000" />      <!-- 线程池维护线程的最大数量 -->  <property name ="maxPoolSize" value ="20" />      <!-- 线程池所缓冲队列数 -->  <property name ="queueCapacity" value ="2000" />  </bean>  

Contoller注入的部分代码

      <property name="taskExecutor" ref="taskExecutor"></property></bean>

Controller的部分代码

<span style="white-space:pre">private ThreadPoolTaskExecutor taskExecutor;public String batchImportSRMProduct2Hybris(final String request) throws Exception {//添加线程到线程池taskExecutor.execute(new TestRunable());taskExecutor.execute(new TestRunable());taskExecutor.execute(new TestRunable());taskExecutor.execute(new TestRunable());taskExecutor.execute(new TestRunable());taskExecutor.execute(new TestRunable());taskExecutor.execute(new TestRunable());taskExecutor.execute(new TestRunable());taskExecutor.execute(new TestRunable());//输出线程池的部分信息                final String info ="thread pool ActiveCount:"+taskExecutor.getActiveCount()+",queue size:"+taskExecutor.getThreadPoolExecutor().getQueue().size()+"Core Pool Size:"+taskExecutor.getCorePoolSize()+"Max Pool Size:"+taskExecutor.getMaxPoolSize();System.out.println(info);return "1111";}public ThreadPoolTaskExecutor getTaskExecutor() {return taskExecutor;}public void setTaskExecutor(final ThreadPoolTaskExecutor taskExecutor) {this.taskExecutor = taskExecutor;}</span>
/**  * 测试Runnable实现类 * * @author sunyx  * @since JDK 1.8  */public class TestRunable implements Runnable {@Overridepublic void run() {for (int i = 0; i < 5; i++) {System.out.println(Thread.currentThread().getName()+","+Thread.currentThread().getId()+"process:"+(i+1)+"/5");try {Thread.sleep(1000);}catch (final InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}}

运行结果


因为之前跑过一次单个的请求,所以多出了10个线程。

200个请求,每个请求执行10个线程,无任何压力啊~~~~~


0 0
原创粉丝点击