基于springboot,当使用某方法时默认调用线程池
启动类
@SpringBootApplication
public class SpringBootApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootApplication .class,args);
}
}
配置线程池类,注意不要忘记注解
@Configuration
@EnableAsync
public class ExecutorConfig {
private static final int corePoolSize = 2; // 核心线程数(默认线程数)
private static final int maxPoolSize = 10; // 最大线程数
private static final int keepAliveTime = 2; // 允许线程空闲时间(单位:默认为秒)
private static final int queueCapacity = 20; // 缓冲队列数
/**
* 默认异步线程池
* @return
*/
@Bean("taskExecutor")
public ThreadPoolTaskExecutor taskExecutor(){
ThreadPoolTaskExecutor pool = new ThreadPoolTaskExecutor();
pool.setThreadNamePrefix("--------------全局线程池-----------------");
pool.setCorePoolSize(corePoolSize);
pool.setMaxPoolSize(maxPoolSize);
pool.setKeepAliveSeconds(keepAliveTime);
pool.setQueueCapacity(queueCapacity);
// 直接在execute方法的调用线程中运行
pool.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
// 初始化
pool.initialize();
return pool;
}
}
需要被多线程调用的方法,需要加注解@async
@Component
public class Thread01 {
@Async("taskExecutor")
public void eat(){
System.out.println(Thread.currentThread().getName()+"线程开吃");
}
}
测试类
@RunWith(SpringRunner.class)
@SpringBootTest
public class test {
@Autowired
Thread01 thread01;
@Test
public void test() {
System.out.println(Thread.currentThread().getName()+"主线程开吃");
thread01.eat();
thread01.eat();
}
}
输出结果
main主线程开吃
--------------全局线程池-----------------1线程开吃
--------------全局线程池-----------------2线程开吃
可知 当调用这个方法时已启用线程池中的线程 就是如此简单