您的位置:首页 > 编程语言 > Java开发

Spring线程池

2016-06-24 12:13 288 查看
最近研究了一下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 {

@Override
public 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 block
e.printStackTrace();
}
}

}

}


运行结果





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



200个请求,每个请求执行10个线程,无任何压力啊~~~~~
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: