闲话省略
spring-config.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:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd"> <!-- 包路径扫描 --> <context:component-scan base-package="com.adao.spring.xmlconfig" /> <!-- Spring线程池 --> <bean id="taskExecutor" class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor"> <!-- 核心线程数 --> <property name="corePoolSize" value="5" /> <!-- 线程池维护线程的最大数量 --> <property name="maxPoolSize" value="10" /> <!-- 允许的空闲时间, 默认60秒 --> <property name="keepAliveSeconds" value="60" /> <!-- 任务队列 --> <property name="queueCapacity" value="50" /> <!-- 线程超过空闲时间限制,均会退出直到线程数量为0 --> <property name="allowCoreThreadTimeOut" value="true" /> <property name="WaitForTasksToCompleteOnShutdown" value="true" /> <!-- 对拒绝task的处理策略 --> <property name="rejectedExecutionHandler"> <bean class="java.util.concurrent.ThreadPoolExecutor.DiscardOldestPolicy" /> </property> </bean> </beans>
app
package com.adao.spring.xmlconfig; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class App { public static void main(String[] args) { ApplicationContext ctx = new ClassPathXmlApplicationContext("Spring-Config.xml"); } }
AdaoTask
package com.adao.spring.xmlconfig; import javax.annotation.PostConstruct; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; import org.springframework.stereotype.Component; import org.springframework.stereotype.Service; //@Component @Service public class AdaoTask { @Autowired private ThreadPoolTaskExecutor executor; @PostConstruct public void testAsycTask() { for (int i = 0; i < 10; i++) { executor.execute(new Runnable() { public void run() { adaoTask(); } }); } } private void adaoTask(){ System.out.println( "Thread Name :" + Thread.currentThread().getName()); } }
@Component 和@Service可以切换
执行结果:
perfect.
转载请注明出处。