Springboot中使用线程池的简单示例

2022-06-21  本文已影响0人  Aaha
1. 配置参数类

配置参数(application.properties中):

thread-pool.corePoolSize=5
thread-pool.maximumPoolSize=100
thread-pool.keepAliveTime=300
thread-pool.queueCapacity=1000

配置参数类:

@Component
@ConfigurationProperties(prefix = "thread-pool")
@ApiModel(value = "线程池配置参数")
@Data
@NoArgsConstructor
public class ThreadPoolConf {
    @ApiModelProperty(value = "核心线程数的最大值")
    private Integer corePoolSize;

    @ApiModelProperty(value = "线程池中能拥有最多线程数")
    private Integer maximumPoolSize;

    @ApiModelProperty(value = "非核心线程空闲存在时间(单位:秒)")
    private Integer keepAliveTime;

    @ApiModelProperty(value = "线程池等待队列最大容量")
    private Integer queueCapacity;
}
2. 创建一个单例模式的线程池类
@Configuration
public class ThreadPoolFactory {
    @Autowired
    private ThreadPoolConf threadPoolConf;
    
    @Bean(name="threadPoolExecutor")
    public ThreadPoolExecutor getThreadPool(){
        // 给线程指定名称,方便查看线程编号
        ThreadFactory namedThreadFactory = new ThreadFactoryBuilder()
                .setNameFormat("conf-thread-pool-%d").build();

        // 创建线程池
        return new ThreadPoolExecutor(threadPoolConf.getCorePoolSize(),
                threadPoolConf.getMaximumPoolSize(),
                threadPoolConf.getKeepAliveTime(),
                TimeUnit.SECONDS,
                new LinkedBlockingQueue<>(threadPoolConf.getQueueCapacity()),
                namedThreadFactory);
}
3. 线程类
public class MyThread implements Runnable {
    private String para1;
    private String para2;
    
    // 构造方法,根据需求自定义
    public MyThread(String para1,  String para2) {
        this.para1 = para1;
        this.para2 = para2;
    }

    @Override
    public void run() {
        //具体执行...
    }
}
4. 使用线程池
//注入线程池类
@Autowired
private ThreadPoolExecutor poolExecutor;

//创建线程并传入参数(在方法中调用下面代码)
MyThread myThread = new MyThread(para1, para2);
poolExecutor.execute(myThread);
上一篇下一篇

猜你喜欢

热点阅读