Spring线程池ThreadPoolTaskExecutor配置及详情
1. ThreadPoolTaskExecutor配置
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
属性字段说明
corePoolSize:线程池维护线程的最少数量
keepAliveSeconds:允许的空闲时间
maxPoolSize:线程池维护线程的最大数量
queueCapacity:缓存队列
rejectedExecutionHandler:对拒绝task的处理策略
2. execute(Runable)方法执行过程
如果此时线程池中的数量小于corePoolSize,即使线程池中的线程都处于空闲状态,也要创建新的线程来处理被添加的任务。
如果此时线程池中的数量等于 corePoolSize,但是缓冲队列 workQueue未满,那么任务被放入缓冲队列。
如果此时线程池中的数量大于corePoolSize,缓冲队列workQueue满,并且线程池中的数量小于maxPoolSize,建新的线程来处理被添加的任务。
如果此时线程池中的数量大于corePoolSize,缓冲队列workQueue满,并且线程池中的数量等于maxPoolSize,那么通过handler所指定的策略来处理此任务。也就是:处理任务的优先级为:核心线程corePoolSize、任务队列workQueue、最大线程 maximumPoolSize,如果三者都满了,使用handler处理被拒绝的任务。
当线程池中的线程数量大于corePoolSize时,如果某线程空闲时间超过keepAliveTime,线程将被终止。这样,线程池可以动态的调整池中的线程数。
3. 示例代码
Junit Test
1 @RunWith(SpringJUnit4ClassRunner.class)2 @ContextConfiguration(classes = { MultiThreadConfig.class})3 public classMultiThreadTest {4
5 @Autowired6 privateThreadPoolTaskExecutor taskExecutor;7
8 @Autowired9 privateMultiThreadProcessService multiThreadProcessService;10
11 @Test12 public voidtest() {13
14 int n = 20;15 for (int i = 0; i < n; i++) {16 taskExecutor.execute(newMultiThreadDemo(multiThreadProcessService));17 System.out.println("int i is " + i + ", now threadpool active threads totalnum is " +taskExecutor.getActiveCount());18 }19
20 try{21 System.in.read();22 } catch(IOException e) {23 throw newRuntimeException(e);24 }25 }26 }
MultiThreadDemo
1 /**
2 * 多线程并发处理demo3 *@authordaniel.zhao4 *5 */
6 public class MultiThreadDemo implementsRunnable {7
8 privateMultiThreadProcessService multiThreadProcessService;9
10 publicMultiThreadDemo() {11 }12
13 publicMultiThreadDemo(MultiThreadProcessService multiThreadProcessService) {14 this.multiThreadProcessService =multiThreadProcessService;15 }16
17 @Override18 public voidrun() {19 multiThreadProcessService.processSomething();20 }21
22 }
MultiThreadProcessService
1 @Service2 public classMultiThreadProcessService {3
4 public static final Logger logger = Logger.getLogger(MultiThreadProcessService.class);5
6 /**
7 * 默认处理流程耗时1000ms8 */
9 public voidprocessSomething() {10 logger.debug("MultiThreadProcessService-processSomething" + Thread.currentThread() + "......start");11 try{12 Thread.sleep(1000);13 } catch(InterruptedException e) {14 throw newRuntimeException(e);15 }16 logger.debug("MultiThreadProcessService-processSomething" + Thread.currentThread() + "......end");17 }18 }
MultiThreadConfig
1 @Configuration2 @ComponentScan(basePackages = { "com.xxx.multithread"})3 @ImportResource(value = { "classpath:config/application-task.xml"})4 @EnableScheduling5 public classMultiThreadConfig {6 }