欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

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());
}