在写框架的时候需要用到线程池,记录下使用方式
ExecutePool配置,开启@EnableAsync支持异步任务
@Configuration
@EnableAsync
public class ExecutorPool {
private int corePoolSize = 10;
private int maxPoolSize = 50;
private int queueSize = 10;
private int keepAlive = 60;
@Bean
public Executor testExecutorPool() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(corePoolSize);
executor.setMaxPoolSize(maxPoolSize);
executor.setQueueCapacity(queueSize);
executor.setKeepAliveSeconds(keepAlive);
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.DiscardPolicy());
executor.setThreadNamePrefix("TestExecutorPool-");
executor.initialize();
return executor;
}
}
执行线程,在调用方法上注解@Async,声明一个异步任务
@Component
public class Tester {
@Async("testExecutorPool")
public void test(){
System.out.println("test---" + Thread.currentThread().getName());
}
}
测试:
@Autowired
private Tester tester;
@Test
public void AsyncTaskTest(){
System.out.println("start---" + Thread.currentThread().getName());
tester.test();
System.out.println("end---" + Thread.currentThread().getName());
}