爲何要用線程池?什麼是線程池?怎麼使用?素質三連!!!spring
線程池核心概念介紹springboot
corePoolSize 正常持有的線程數。在使用線程時,若是池中的線程數小於該數,會建立新線程
maximumPoolSize 容許擁有的最大線程數。 池中核心線程core若是超出了,會放到阻塞隊列中。隊列若是也滿了,會申請建立線程但數量不能超過該數值。若是超過了會執行拒絕策略
BlockingQueue<Runnable> workQueue 阻塞隊列,用於存放等待資源的線程。
long keepAliveTime,TimeUnit unit 大於核心線程數的線程空閒以後的存活時間。活着浪費空氣
實際配置以下 多線程
@EnableConfigurationProperties public class MerchantApplication { public static void main(String[] args) { SpringApplication.run(MerchantApplication.class, args); } } <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-configuration-processor</artifactId> <optional>true</optional> </dependency>
配置啓動加載時須要的類。1.yml配置屬性。2.配置類啓動加載app
// yml配置 task: pool: corePoolSize: 5 queueCapacity: 20 maxPoolSize: 10 keepAliveSeconds: 3 // 屬性映射類 @Data @ConfigurationProperties(prefix = "task.pool") @Component public class TaskThreadPoolProperty { private int corePoolSize; private int maxPoolSize; private int keepAliveSeconds; private int queueCapacity; }
// 啓動加載
@Configuration
@EnableAsync
public class ThreadPoolConfig {
@Resource
private TaskThreadPoolProperty config;
/**
* 默認使用 名爲 taskExecutor 的線程池
*
* @return 初始化線程池
*/
@Bean("taskExecutor")
public Executor configTaskAsyncPool() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
//核心線程池大小
executor.setCorePoolSize(config.getCorePoolSize());
//最大線程數
executor.setMaxPoolSize(config.getMaxPoolSize());
//隊列容量
executor.setQueueCapacity(config.getQueueCapacity());
//活躍時間
executor.setKeepAliveSeconds(config.getKeepAliveSeconds());
//線程名字前綴
executor.setThreadNamePrefix("Qc-");
// CallerRunsPolicy:不在新線程中執行任務,而是由調用者所在的線程來執行
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
executor.setWaitForTasksToCompleteOnShutdown(true);
return executor;
}
}
// 實現異步操做的類 @Component public class AsyncMessage { @Async public void sendMsgCL(String mobile, String content) { try { Thread.sleep(3000L); System.out.println("多線程異步執行" + " " + Thread.currentThread().getName()); } catch (InterruptedException e) { e.printStackTrace(); } } } // 測試異步的接口 @Resource private AsyncMessage message; @PostMapping("/data1") public void data() { message.sendMsgCL(null, null); System.out.println("haha"); }