Springboot线程池配置管理

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/a787373009/article/details/101625265

Springboot线程池配置管理

1. 线程池配置类

package com.bin.kong.csdnspider.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.AsyncTaskExecutor;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.ThreadPoolExecutor;
@Configuration
@EnableAsync
public class ThreadPoolConfig {
    private int corePoolSize = 10;//线程池维护线程的最少数量
    private int maxPoolSize = 50;//线程池维护线程的最大数量
    private int queueCapacity = 20; //缓存队列
    private int keepAlive = 120;//允许的空闲时间
    @Bean
    public AsyncTaskExecutor threadExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(corePoolSize);
        executor.setMaxPoolSize(maxPoolSize);
        executor.setQueueCapacity(queueCapacity);
        executor.setThreadNamePrefix("threadExecutor-");
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); //对拒绝task的处理策略
        executor.setKeepAliveSeconds(keepAlive);
        executor.initialize();
        return executor;
    }
}

配置说明:

配置项 说明
corePoolSize 最小的线程数,缺省:1
maxPoolSize 最大的线程数,缺省:Integer.MAX_VALUE
queueCapacity 当线程池中最小的线程数被占用满后,新的任务会被放进队列queue里面,当这个queue的capacity也被占满之后,pool里面会创建新线程处理这个任务,直到总线程数达到了最大线程数maxsize,这时系统会拒绝这个任务并抛出TaskRejectedException异常(缺省配置的情况下,可以通过rejection-policy来决定如何处理这种情况)。缺省值为:Integer.MAX_VALUE
keepAlive 超过corePoolSize最小线程数的那些线程,任务完成后,再经过这个设置的时长(单位:秒)会被结束掉,这样的话线程池可以动态的调整池中的线程数
rejection-policy ABORT(缺省):抛出TaskRejectedException异常,然后不执行;DISCARD:不执行,也不抛出异常即放弃该线程;DISCARD_OLDEST:丢弃queue中最旧的那个任务;CALLER_RUNS:不在新线程中执行任务,而是由调用者所在的线程来执行(不再异步)

2.线程池的使用

在类中的方法名上使用:@Async(“threadExecutor”) 即可达到使用线程池的效果
示例如下:

package com.bin.kong.csdnspider.utils;
import org.springframework.scheduling.annotation.Async;
@Service
public class TestThreadPool {
    @Async("threadExecutor")
    public void exec() {
        System.out.println("当前线程名:"+Thread.currentThread().getName());
    }
}

测试打印结果如下:

当前线程名:threadExecutor-1

猜你喜欢

转载自blog.csdn.net/a787373009/article/details/101625265