1 场景
@Async用于异步处理
2 使用
@Async作用于方法上
@Async
public void testAsync() {
log.info("testAsync");
}
@EnableAsync在主类
@EnableAsync
@SpringBootApplication
public class TestApplication
{
public static void main( String[] args )
{
SpringApplication.run(TestApplication.class, args);
}
}
3 默认线程池
默认使用Spring创建ThreadPoolTaskExecutor。
默认核心线程数:8,
最大线程数:Integet.MAX_VALUE,
队列使用LinkedBlockingQueue,
容量是:Integet.MAX_VALUE,
空闲线程保留时间:60s,
线程池拒绝策略:AbortPolicy。
问题:并发情况下,会无线创建线程
解决:自定义配置参数
spring:
task:
execution:
pool:
max-size: 6
core-size: 3
keep-alive: 3s
queue-capacity: 1000
thread-name-prefix: name
4 自定义线程池
编写配置类
@Configuration
@Data
public class ExecutorConfig{
/**
* 核心线程
*/
private int corePoolSize;
/**
* 最大线程
*/
private int maxPoolSize;
/**
* 队列容量
*/
private int queueCapacity;
/**
* 保持时间
*/
private int keepAliveSeconds;
/**
* 名称前缀
*/
private String preFix;
@Bean
public Executor myExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(corePoolSize);
executor.setMaxPoolSize(maxPoolSize);
executor.setQueueCapacity(queueCapacity);
executor.setKeepAliveSeconds(keepAliveSeconds);
executor.setThreadNamePrefix(preFix);
executor.setRejectedExecutionHandler( new ThreadPoolExecutor.AbortPolicy());
executor.initialize();
return executor;
}
}
使用
@Async("myExecutor")
public void testAsync() {
log.info("testAsync");
}