配置方法如下:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="threadPoolTaskExecutor" class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor">
<!-- 核心線程數 -->
<property name="corePoolSize" value="2" />
<!-- 最大線程數 -->
<property name="maxPoolSize" value="10" />
<!-- 隊列最大長度 >=mainExecutor.maxSize -->
<property name="queueCapacity" value="1000" />
<!-- 線程池維護線程所允許的空閑時間 -->
<property name="keepAliveSeconds" value="60" />
<!-- 線程池對拒絕任務(無線程可用)的處理政策 -->
<property name="rejectedExecutionHandler">
<bean class="java.util.concurrent.ThreadPoolExecutor$CallerRunsPolicy" />
</property>
</bean>
</beans>
使用方法:
public class LishikuanApplicationTests {
@Autowired
private ThreadPoolTaskExecutor threadPoolTaskExecutor;
@Test
public void contextLoads() {
for (int i = 0; i < 10; i++) {
threadPoolTaskExecutor.submit(new TaskThread(i));
//擷取可用核心線程
System.out.println( "activeAcount:" + threadPoolTaskExecutor.getActiveCount());
}
}
public class TaskThread implements Runnable{
private int num;
public TaskThread(int num) {
this.num = num;
}
@Override
public void run() {
System.out.println("num : " + num);
}
}
}