技术程序员

Spring Boot 配置和使用多线程池

2018-06-07  本文已影响517人  阿懒土灵

某些情况下,我们需要在项目中对多种任务分配不同的线程池进行执行。从而通过监控不同的线程池来控制不同的任务。为了达到这个目的,需要在项目中配置多线程池。

spring boot 提供了简单高效的线程池配置和使用方案。

配置

首先是配置线程池的bean交给spring 管理:

@Configuration

public 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");
        //当任务数量超过MaxPoolSize和QueueCapacity时使用的策略,该策略是又调用任务的线程执行
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());

        executor.initialize();

        return executor;

    }

}


使用

使用线程只需要在执行方法上加上注释,同时该方法的类必须被定义为bean,交由spring管理。
可以在类上使用注解@Component、@Service等

@Async(value="ThreadPoolA")
public void taskA(){
  ...
}

查看线程活跃数:

@Autowired
    private ThreadPoolTaskExecutor threadPoolA;//变量名称为定义的线程池bean定义的name属性名。

public void checkAvtiveThreadNum() {
        int num = threadPoolA.getActiveCount();
}

当然还有其他一些方法,这里不再举例。


线程池各属性理解:

corePoolSize:表示线程池核心线程,正常情况下开启的线程数量。

queueCapacity:当核心线程都在跑任务,还有多余的任务会存到此处。

maxPoolSize:如果queueCapacity存满了,还有任务就会启动更多的线程,直到线程数达到maxPoolSize。如果还有任务,则根据拒绝策略进行处理。

拒绝策略有多种:

上一篇 下一篇

猜你喜欢

热点阅读