spring boot自定义线程池

一、自定义线程池

@Configuration
@EnableAsync
//可以异步执行,就是开启多线程的意思。
public class TaskExecutePool {
    @Autowired
    private TaskThreadPoolConfig config;
    @Bean
    public Executor myTaskAsyncPool(){
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(config.getCorePoolSize());
        //核心线程池大小
        executor.setMaxPoolSize(config.getMaxPoolSize());
        //最大线程数
        executor.setQueueCapacity(config.getQueueCapacity());
        //队列容量
        executor.setKeepAliveSeconds(config.getKeepAliveSeconds());
        //活跃时间
        executor.setThreadNamePrefix("MyExecutor-");
        //线程名字前缀
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        //当当pool已经到达max size的时候,如何处理新任务,CallerRunsPolicy,由调用者所在的线程执行
        executor.initialize();
        return  executor;
    }
}

1.2 线程池配置类


@Component
//线程池配置类
public class TaskThreadPoolConfig {
    @Value("${task.pool.corePoolSize}")
    private int corePoolSize;
    @Value("${task.pool.maxPoolSize}")
    private int maxPoolSize;
    @Value("${task.pool.keepAliveSeconds}")
    private int keepAliveSeconds;
    @Value("${task.pool.queueCapacity}")
    private int queueCapacity;

    public int getCorePoolSize() {
        return corePoolSize;
    }

    public void setCorePoolSize(int corePoolSize) {
        this.corePoolSize = corePoolSize;
    }

    public int getMaxPoolSize() {
        return maxPoolSize;
    }

    public void setMaxPoolSize(int maxPoolSize) {
        this.maxPoolSize = maxPoolSize;
    }

    public int getKeepAliveSeconds() {
        return keepAliveSeconds;
    }

    public void setKeepAliveSeconds(int keepAliveSeconds) {
        this.keepAliveSeconds = keepAliveSeconds;
    }

    public int getQueueCapacity() {
        return queueCapacity;
    }

    public void setQueueCapacity(int queueCapacity) {
        this.queueCapacity = queueCapacity;
    }
}

1.3 yum配置文件

task:
  pool:
    corePoolSize: 500
    maxPoolSize: 1000
    keepAliveSeconds: 300
    queueCapacity: 50

1.4 需要异步线程执行的任务

@Component
//需要异步线程执行的任务
public class AsyncTask {
    protected final Logger logger = LoggerFactory.getLogger(this.getClass());
    @Async("myTaskAsyncPool")//myTaskAsyncPool,配置线程池的方法名
    public void doTask1(int i){
        logger.info("Task" + i + "started");
    }
    @Async //使用默认的线程池
    public void doTask2(int i){
        if(i == 0){
            throw new NullPointerException();
        }
        logger.info("Task2" + i + "started");
    }
}

1.5 测试


@RunWith(SpringRunner.class)
@SpringBootTest
public class TaskExecutePoolTest {
    @Autowired
    AsyncTask asyncTask;
    @Test
    public void AsyncTaskTest(){
        for (int i = 0; i < 50; i++) {
            asyncTask.doTask1(i);
            asyncTask.doTask2(i);
        }
        System.out.println("结束调用");
    }
}

参考文章:https://mp.weixin.qq.com/s/pTS57WpZksA8_cDqv6ZXEg

你可能感兴趣的:(Spring,boot)