java config方式配置spring线程池

配置文件:thread.properties

//线程池维护线程的最少数量
spring.corePoolSize=5
//允许的空闲时间
spring.keepAliveSeconds=200
//线程池维护线程的最大数量
spring.maxPoolSize=10
//缓存队列
spring.queueCapacity=20

代码:

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.task.TaskExecutor;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * spring线程池配置
 */
@Configuration
@PropertySource("classpath:thread.properties")
public class ThreadConfig {

    //线程池维护线程的最少数量
    @Value("${spring.corePoolSize}")
    private Integer corePoolSize;
    //允许的空闲时间
    @Value("${spring.keepAliveSeconds}")
    private Integer keepAliveSeconds;
    //线程池维护线程的最大数量
    @Value("${spring.maxPoolSize}")
    private Integer maxPoolSize;
    //缓存队列
    @Value("${spring.queueCapacity}")
    private Integer queueCapacity;

    @Bean
    public TaskExecutor taskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(corePoolSize);
        executor.setKeepAliveSeconds(keepAliveSeconds);
        executor.setMaxPoolSize(maxPoolSize);
        executor.setQueueCapacity(queueCapacity);
        ThreadPoolExecutor.CallerRunsPolicy callerRunsPolicy = new ThreadPoolExecutor.CallerRunsPolicy();
        //对拒绝task的处理策略
        executor.setRejectedExecutionHandler(callerRunsPolicy);
        executor.initialize();
        return executor;
    }


}

使用:

注入

@Autowired
private TaskExecutor taskExecutor;

测试:
taskExecutor.execute(new Runnable() {
            @Override
            public void run() {
                for(int i=0;i<100;i++){
                    System.out.println("---------------------------"+i);
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值