近来因为工作需要研究了下spring线程池,结合spring IoC的强大威力,很方便的实现了多线程的创建和执行!
spring-thread.xml配置文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xmlns:security="http://www.springframework.org/schema/security"
xsi:schemaLocation="
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-3.2.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/data/jpa
http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd">
<!-- Activates annotation-based bean configuration -->
<context:annotation-config />
<bean id="taskExecutorPool"
class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor">
<!-- 核心线程数,默认为1-->
<property name="corePoolSize" value="10" />
<!-- 最大线程数,默认为Integer.MAX_VALUE-->
<property name="maxPoolSize" value="50" />
<property name="queueCapacity" value="1000" />
<!-- 线程池维护线程所允许的空闲时间,默认为60s-->
<property name="keepAliveSeconds" value="300" />
<property name="rejectedExecutionHandler">
<bean class="java.util.concurrent.ThreadPoolExecutor$CallerRunsPolicy" />
</property>
</bean>
<!-- 这里指定异步执行器的类-->
<!-- 原作者在这里没有指定具体的类,class="com.vinux.framework.thread.impl" -->
<!-- 推测作者的目的是自己编写和维护异步执行器来完成自定义的功能! -->
<bean id="asynchExecutor" class="com.vinux.framework.thread.impl.AsynchExecutor" scope="prototype"/>
</beans>
java测试代码:
public class ThreadTaskDemo implements Runnable{
public ThreadTaskDemo(){
}
@Override
public void run() {
System.out.println("执行审核结束时间的扫表工作!");
}
}
public class ThreadPoolTaskExecutorTest
extends BaseSpringJUnitTest {
@Autowired
private ThreadPoolTaskExecutor taskExecutorPool;
// @Autowired
// private IAsynchExecutor asynchExecutor;
@Test
public void test(){
taskExecutorPool.execute(new ThreadTaskDemo());
}
}
我用线程池异步执行定时任务,在每天凌晨时刻扫描表中审核时间到了的数据,使用存储过程将到时间的数据进行进一步处理!