定義線程池
第一步,先定義一個線程池,比如:
@Configuration
public class PoolConfig {
@Bean("testExecutor")
public Executor testExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(10);
executor.setMaxPoolSize(20);
executor.setQueueCapacity(200);
executor.setKeepAliveSeconds(60);
executor.setThreadNamePrefix("testExecutor-");
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
return executor;
}
}
@EnableAsync這個注解如果在啟動類已經添加過,就無需再次添加.
上面我們通過使用ThreadPoolTaskExecutor創建了一個線程池,同時設置了以下這些參數:
- 核心線程數10:線程池創建時候初始化的線程數
- 最大線程數20:線程池最大的線程數,只有在緩沖隊列滿了之后才會申請超過核心線程數的線程
- 緩沖隊列200:用來緩沖執行任務的隊列
- 允許線程的空閑時間60秒:當超過了核心線程出之外的線程在空閑時間到達之后會被銷毀
- 線程池名的前綴:設置好了之后可以方便我們定位處理任務所在的線程池
- 線程池對拒絕任務的處理策略:這里采用了CallerRunsPolicy策略,當線程池沒有處理能力的時候,該策略會直接在 execute 方法的調用線程中運行被拒絕的任務;如果執行程序已關閉,則會丟棄該任務
使用線程池
在定義了線程池之后,我們如何讓異步調用的執行任務使用這個線程池中的資源來運行呢?方法非常簡單,我們只需要在@Async注解中指定線程池名即可,比如:
@Slf4j
@Service
public class TestMethod {
public static Random random = new Random();
@Async("testExecutor")
public void one() throws Exception {
log.info("第一個");
long start = System.currentTimeMillis();
Thread.sleep(random.nextInt(10000));
long end = System.currentTimeMillis();
log.info("完成一,耗時:" + (end - start) + "毫秒");
}
@Async("testExecutor")
public void two() throws Exception {
log.info("第二個");
long start = System.currentTimeMillis();
Thread.sleep(random.nextInt(10000));
long end = System.currentTimeMillis();
log.info("完成二,耗時:" + (end - start) + "毫秒");
}
@Async("testExecutor")
public void three() throws Exception {
log.info("第三個");
long start = System.currentTimeMillis();
Thread.sleep(random.nextInt(10000));
long end = System.currentTimeMillis();
log.info("完成三,耗時:" + (end - start) + "毫秒");
}
}
單元測試
最后,我們來寫個單元測試來驗證一下
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
public class TestApplicationTests {
@Autowired
private TestMethod testMethod;
@Test
public void test() throws Exception {
testMethod.one();
testMethod.two();
testMethod.three();
Thread.currentThread().join();
}
}
執行上面的單元測試,我們可以在控制台中看到所有輸出的線程名前都是之前我們定義的線程池前綴名開始的,說明我們使用線程池來執行異步任務的試驗成功了!
2019-05-24 09:21:24.544 INFO 10756 --- [ testExecutor-2] c.a.authorization_java.util.TestMethod : 第二個
2019-05-24 09:21:24.543 INFO 10756 --- [ testExecutor-1] c.a.authorization_java.util.TestMethod : 第一個
2019-05-24 09:21:24.544 INFO 10756 --- [ testExecutor-3] c.a.authorization_java.util.TestMethod : 第三個
2019-05-24 09:21:26.868 INFO 10756 --- [ testExecutor-3] c.a.authorization_java.util.TestMethod : 完成三,耗時:2324毫秒
2019-05-24 09:21:29.774 INFO 10756 --- [ testExecutor-2] c.a.authorization_java.util.TestMethod : 完成二,耗時:5230毫秒
2019-05-24 09:21:31.628 INFO 10756 --- [ testExecutor-1] c.a.authorization_java.util.TestMethod : 完成一,耗時:7084毫秒