一直不太忙白线程池在实际应用中到底扮演什么样得角色,有什么场景可以使用到,只有真正做项目中使用到了才逐渐理解。
使用多线程,往往是创建Thread
,或者是实现Runnable
接口,用到线程池得时候需要创建Executors
,通过使用@EnableAsync
注解就可以使用多线程,@Async
注解加在线程任务的方法上 可以异步执行任务。使用 ThreadPoolTaskExecutor
就可以使用线程池。
定义配置类
这个配置类需要实现AsyncConfigurer
接口,并实现他的方法
- 异步线程的提供者,在里面配置自动执行的东西,如线程池参数。
- 线程异常的处理。
@Configuration
@EnableAsync
public class ThreadPoolConfig implements AsyncConfigurer {
private static final Logger log = LoggerFactory.getLogger(ThreadPoolConfig.class);
@Autowired
private ThreadPoolParamsConfig threadPoolParamsConfig;
@Override
@Bean("taskExecutor")
public Executor getAsyncExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(threadPoolParamsConfig.getCorePoolSize());
executor.setMaxPoolSize(threadPoolParamsConfig.getMaxPoolSize());
executor.setQueueCapacity(threadPoolParamsConfig.getQueueCapacity());
executor.setKeepAliveSeconds(threadPoolParamsConfig.getKeepAliveSeconds());
executor.setThreadNamePrefix("authority-manage-thread-");
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
executor.initialize();
return executor;
}
@Override
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
return (ex,method,params) -> {
log.error("异常信息:{}",ex.getMessage());
log.error("exception method:{}",method.getName());
};
}
}
线程池配置类
@Data
@Component
@ConfigurationProperties(prefix = "task.pool")
public class ThreadPoolParamsConfig {
/**
* 核心线程数
*/
private int corePoolSize;
/**
* 最大线程数
*/
private int maxPoolSize;
/**
* 线程空闲空间
*/
private int keepAliveSeconds;
/**
* 任务队列容量
*/
private int queueCapacity;
}
调用异步线程任务
/**
* 测试异步创建任务
* @return
*/
public Result createIsueTask() {
inspPlanRlnToolService.asynsBatchCreateIsueTasks();
return Result.ok();
}
线程任务类
/**
* 异步创建任务
*/
@Async("taskExecutor")
@Override
public void asynsBatchCreateIsueTasks() {
log.info("这是一个异步任务");
}