Spring Boot之线程池
程序员文章站
2022-05-01 13:04:05
...
在写框架的时候需要用到线程池,记录下使用方式
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());
}
推荐阅读
-
浅谈Spring @Async异步线程池用法总结
-
Spring Boot实战之逐行释义Hello World程序
-
spring boot之SpringApplication 事件监听
-
在spring boot中使用java线程池ExecutorService的讲解
-
Spring Boot使用Druid连接池的示例代码
-
Spring Boot基础入门之基于注解的Mybatis
-
Spring Boot 配置和使用多线程池的实现
-
深入Spring Boot之ClassLoader的继承关系和影响
-
Spring Boot实战之数据库操作的示例代码
-
Java concurrency线程池之线程池原理(一)_动力节点Java学院整理