多线程执行过程缓存
1. 若是此时线程池中的数量小于corePoolSize,即便线程池中的线程都处于空闲状态,也要建立新的线程来处理被添加的任务。 2. 若是此时线程池中的数量等于corePoolSize,可是缓冲队列 workQueue未满,那么任务被放入缓冲队列。 3. 若是此时线程池中的数量大于corePoolSize,缓冲队列workQueue满,而且线程池中的数量小于maxPoolSize,建新的线程来处理被添加的任务。 4. 若是此时线程池中的数量大于corePoolSize,缓冲队列workQueue满,而且线程池中的数量等于maxPoolSize,那么经过handler所指定的策略来处理此任务。也就是:处理任务的优先级为:核心线程corePoolSize、任务队列workQueue、最大线程 maximumPoolSize,若是三者都满了,使用handler处理被拒绝的任务。 5. 当线程池中的线程数量大于corePoolSize时,若是某线程空闲时间超过keepAliveTime,线程将被终止。这样,线程池能够动态的调整池中的线程数。
配置类多线程
/** * [@author](https://my.oschina.net/arthor) Mr.Krab * [@date](https://my.oschina.net/u/2504391) 2019-03-05 09:39 */ @Configuration @EnableAsync // 启用多线程 public class AsyncConfig { [@Bean](https://my.oschina.net/bean) public Executor getExecutor() { ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); // 线程池维护线程的最少数量 executor.setCorePoolSize(5); // 线程池维护线程的最大数量 executor.setMaxPoolSize(10); // 缓存队列 executor.setQueueCapacity(25); // 线程池初始化 executor.initialize(); return executor; } }
异步任务异步
/** * @author Mr.Krab * @date 2019-03-05 09:45 */ @Service @Slf4j public class AsyncService { @Async //异步任务 public void executeAsync(int i) { log.info("current thread {}, i = {}", Thread.currentThread().getName(), i); } }
测试类async
/** * @author Mr.Krab * @date 2019-03-05 09:48 */ @RunWith(SpringRunner.class) @SpringBootTest public class AsyncTest { @Autowired private AsyncService asyncService; @Test public void testAsync(){ for(int i =0; i< 10;i++){ asyncService.executeAsync(i); } } }
执行结果测试
2019-03-05 09:55:10.470 INFO 18644 --- [ getExecutor-4] cn.misterkrab.demo.async.AsyncService : current thread getExecutor-4, i = 3 2019-03-05 09:55:10.470 INFO 18644 --- [ getExecutor-5] cn.misterkrab.demo.async.AsyncService : current thread getExecutor-5, i = 4 2019-03-05 09:55:10.470 INFO 18644 --- [ getExecutor-1] cn.misterkrab.demo.async.AsyncService : current thread getExecutor-1, i = 0 2019-03-05 09:55:10.470 INFO 18644 --- [ getExecutor-3] cn.misterkrab.demo.async.AsyncService : current thread getExecutor-3, i = 2 2019-03-05 09:55:12.163 INFO 18644 --- [ getExecutor-1] cn.misterkrab.demo.async.AsyncService : current thread getExecutor-1, i = 7 2019-03-05 09:55:10.470 INFO 18644 --- [ getExecutor-2] cn.misterkrab.demo.async.AsyncService : current thread getExecutor-2, i = 1 2019-03-05 09:55:11.019 INFO 18644 --- [ getExecutor-4] cn.misterkrab.demo.async.AsyncService : current thread getExecutor-4, i = 5 2019-03-05 09:55:11.715 INFO 18644 --- [ getExecutor-5] cn.misterkrab.demo.async.AsyncService : current thread getExecutor-5, i = 6 2019-03-05 09:55:12.587 INFO 18644 --- [ getExecutor-3] cn.misterkrab.demo.async.AsyncService : current thread getExecutor-3, i = 8 2019-03-05 09:55:13.651 INFO 18644 --- [ getExecutor-1] cn.misterkrab.demo.async.AsyncService : current thread getExecutor-1, i = 9