Spring已经实现的异常线程池:
1. SimpleAsyncTaskExecutor:不是真的线程池,这个类不重用线程,每次调用都会创建一个新的线程
2. SyncTaskExecutor:这个类没有实现异步调用,只是一个同步操作。只适用于不需要多线程的地方
3. ConcurrentTaskExecutor:Executor的适配类,不推荐使用。如果ThreadPoolTaskExecutor不满足要求时,才用考虑使用这个类
4. SimpleThreadPoolTaskExecutor:是Quartz的SimpleThreadPool的类。线程池同时被quartz和非quartz使用,才需要使用此类
5. ThreadPoolTaskExecutor :最常使用, 其实质是对java.util.concurrent.ThreadPoolExecutor的包装
Spring有两种方法启动配置线程池
1. 注解
2. XML
1.1 通过注解实现
要启动异常方法还需要以下配置
@EnableAsync 此注解开户异步调用功能
/**
* 异步 线程池
* spring异步线程池的接口类,其实质是Java.util.concurrent.Executor
* @return
*/
@Configuration
@EnableAsync // 启动异步调用
public class ThreadPoolConfig {
@Autowired
private Environment environment;
private final String testExecutor = "testExecutor";
private static final Logger logger = LoggerFactory.getLogger(ThreadPoolConfig.class);
@Bean(testExecutor)
public Executor getAsyncExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); //不调用重写的线程池
//配置核心线程数
executor.setCorePoolSize(Integer.parseInt(environment.getProperty("executor.corePoolSize")));
//配置最大线程数
executor.setMaxPoolSize(Integer.parseInt(environment.getProperty("executor.maxPoolSize")));
//配置队列大小
executor.setQueueCapacity(Integer.parseInt(environment.getProperty("executor.queueCapacity")));
//配置线程池的线程的名称前缀 如果不定义,则使用系统默认的线程池
executor.setThreadNamePrefix("async-testThread-");
//设置拒绝策略
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
//设置线程的空闲时间,达到了就删除这个线程
executor.setKeepAliveSeconds(10);
//执行初始化
executor.initialize();
logger.info("线程池初始化....");
return executor;
}
}
配置文件:
#线程池配置
executor.corePoolSize = 10
executor.maxPoolSize = 30
executor.queueCapacity = 5
使用方法:
/**
* 最简单的异步调用,直接用注解
*/
@Async(“testExecutor”)
public void asyncInvokeSimplest() {
log.info("线程池在使用。。。。");
}