<!-- spring线程池 -->
<bean id = "task" class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor">
<!-- 线程池维护线程的最少数量 -->
<property name="corePoolSize" value="2"></property>
<!-- 允许空闲时间 -->
<property name="keepAliveSeconds" value="200"></property>
<!-- 线程池维护线程的最大数量 -->
<property name="maxPoolSize" value="5"></property>//配置为5,实际最大线程为maxPoolSize+1=6
<!-- 缓存队列 -->
<property name="queueCapacity" value="1"></property>
<!-- 对拒绝task的处理策略 -->
<property name="rejectedExecutionHandler">
<bean class="java.util.concurrent.ThreadPoolExecutor$CallerRunsPolicy" />
</property>
</bean>
如下测试
@Controller
@RequestMapping("/")
public class index {
@Autowired
private TaskExecutor task; //如上在spring配置文件中配置该线程池信息,名字要与配置文件中bean的id一样
@RequestMapping(value = "/tx1", method = RequestMethod.GET)
@ResponseBody
public String tx1(){
int i =0;
while(i < 8){
i++;
task.execute(new Thread(){
public void run() {
System.out.println("===="+index.this.hashCode()+"====="+Thread.currentThread().hashCode());
int a = 0;
while(a < 3){
try {
Thread.sleep(1000);
a++;
System.out.println(Thread.currentThread().hashCode()+":"+a);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(name+"==========结束==========");
};
});
}
return "index";
}
}
测试结果如下:同时进行的线程最大为6个线程,其它任务需要等线程处理完再进行
====261098527=====1258663477
====261098527=====2001246553
====261098527=====901774565
====261098527=====1542691695
====261098527=====1657056902
====261098527=====2038668338
1258663477:1
2038668338:1
1657056902:1
1542691695:1
901774565:1
2001246553:1
1258663477:2
2038668338:2
1657056902:2
1542691695:2
901774565:2
2001246553:2
1258663477:3
0==========结束==========
====261098527=====1258663477
2038668338:3
0==========结束==========
====261098527=====2038668338
1657056902:3
0==========结束==========
1542691695:3
0==========结束==========
901774565:3
0==========结束==========
2001246553:3
0==========结束==========
2038668338:1
1258663477:1
2038668338:2
1258663477:2
2038668338:3
0==========结束==========
1258663477:3
0==========结束==========