@Configuration
@EnableAsync
//可以异步执行,就是开启多线程的意思。
public class TaskExecutePool {
@Autowired
private TaskThreadPoolConfig config;
@Bean
public Executor myTaskAsyncPool(){
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(config.getCorePoolSize());
//核心线程池大小
executor.setMaxPoolSize(config.getMaxPoolSize());
//最大线程数
executor.setQueueCapacity(config.getQueueCapacity());
//队列容量
executor.setKeepAliveSeconds(config.getKeepAliveSeconds());
//活跃时间
executor.setThreadNamePrefix("MyExecutor-");
//线程名字前缀
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
//当当pool已经到达max size的时候,如何处理新任务,CallerRunsPolicy,由调用者所在的线程执行
executor.initialize();
return executor;
}
}
1.2 线程池配置类
@Component
//线程池配置类
public class TaskThreadPoolConfig {
@Value("${task.pool.corePoolSize}")
private int corePoolSize;
@Value("${task.pool.maxPoolSize}")
private int maxPoolSize;
@Value("${task.pool.keepAliveSeconds}")
private int keepAliveSeconds;
@Value("${task.pool.queueCapacity}")
private int queueCapacity;
public int getCorePoolSize() {
return corePoolSize;
}
public void setCorePoolSize(int corePoolSize) {
this.corePoolSize = corePoolSize;
}
public int getMaxPoolSize() {
return maxPoolSize;
}
public void setMaxPoolSize(int maxPoolSize) {
this.maxPoolSize = maxPoolSize;
}
public int getKeepAliveSeconds() {
return keepAliveSeconds;
}
public void setKeepAliveSeconds(int keepAliveSeconds) {
this.keepAliveSeconds = keepAliveSeconds;
}
public int getQueueCapacity() {
return queueCapacity;
}
public void setQueueCapacity(int queueCapacity) {
this.queueCapacity = queueCapacity;
}
}
@Component
//需要异步线程执行的任务
public class AsyncTask {
protected final Logger logger = LoggerFactory.getLogger(this.getClass());
@Async("myTaskAsyncPool")//myTaskAsyncPool,配置线程池的方法名
public void doTask1(int i){
logger.info("Task" + i + "started");
}
@Async //使用默认的线程池
public void doTask2(int i){
if(i == 0){
throw new NullPointerException();
}
logger.info("Task2" + i + "started");
}
}
1.5 测试
@RunWith(SpringRunner.class)
@SpringBootTest
public class TaskExecutePoolTest {
@Autowired
AsyncTask asyncTask;
@Test
public void AsyncTaskTest(){
for (int i = 0; i < 50; i++) {
asyncTask.doTask1(i);
asyncTask.doTask2(i);
}
System.out.println("结束调用");
}
}