多線程執行過程緩存
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