In some cases, we need to assign different thread pools to execute multiple tasks in the project. Therefore, different tasks are controlled by monitoring different thread pools. To achieve this, a multi-threaded pool is required to be configured in the project.
spring boot provides simple and efficient thread pool configuration and usage solutions.
Configuration
First, configure the thread pool beans to be handed over to spring management:
@Configurationpublic class TaskExecutePool { @Bean(name ="threadPoolA")public ThreadPoolTaskExecutormyTaskAsyncPool() {ThreadPoolTaskExecutor executor =new ThreadPoolTaskExecutor(); executor.setCorePoolSize(4); executor.setMaxPoolSize(8); executor.setQueueCapacity(100); executor.setKeepAliveSeconds(60); executor.setThreadNamePrefix("Pool-A"); executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); executor.initialize(); return executor; }@Bean(name ="ThreadPoolB")public ThreadPoolTaskExecutorAsyncPoolB() {ThreadPoolTaskExecutor executor =new ThreadPoolTaskExecutor(); executor.setCorePoolSize(2); executor.setMaxPoolSize(4); executor.setQueueCapacity(8); executor.setKeepAliveSeconds(60); executor.setThreadNamePrefix("Pool-B"); //The policy used when the number of tasks exceeds MaxPoolSize and QueueCapacity. This policy is to call the thread of the task to execute executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); executor.initialize(); return executor; }} use
Using threads only requires annotation on the execution method, and the class of the method must be defined as a bean and handed over to spring to manage.
You can use annotations @Component, @Service, etc. on the class
@Async(value="ThreadPoolA")public void taskA(){ ...} Check the number of threads active:
@Autowired private ThreadPoolTaskExecutor threadPoolA;//The variable name is the name of the defined thread pool bean name. public void checkAvtiveThreadNum() { int num = threadPoolA.getActiveCount();}Of course there are other methods, so I won’t give any examples here.
Understanding of each attribute of thread pool:
corePoolSize: represents the thread pool core thread, and the number of threads opened under normal circumstances.
queueCapacity: When the core threads are running tasks, there are still extra tasks that will be saved here.
maxPoolSize: If queueCapacity is full, more threads will be started until the number of threads reaches maxPoolSize. If there are still tasks, it will be processed according to the rejection policy.
There are many rejection strategies:
The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.