标签:async framework ESS 大小 handler ali dex etc stat
为什么要用线程池?什么是线程池?怎么使用?素质三连!!!
线程池核心概念介绍
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.配置类启动加载
// 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"); }
标签:async framework ESS 大小 handler ali dex etc stat
原文地址:https://www.cnblogs.com/nightOfStreet/p/11899659.html