多线程的基本使用

1、配置文件中线程池的参数

//corePoolSize 线程池核心线程大小
test.corePoolSize=20
//maxPoolSize 线程池最大线程数量
test.maxPoolSize=40
//keepAliveTime 空闲线程存活时间
test.keepAliveSeconds=300
//queueCapacity 缓存队列容量
test.queueCapacity=50

2、线程配置config类

@Configuration  //声明配置类
@EnableAsync  //标记
public class ExcutorConfig {
  @Value("${test.corePoolSize}")
  private int corePoolSize;
  @Value("${test.maxPoolSize}")
  private int maxPoolSize;
  @Value("${test.keepAliveSeconds}")
  private int keepAliveSeconds;
  @Value("${test.queueCapacity}")
  private int queueCapacity;

  @Bean("taskExecutor")//调用线程时的线程名字
  public Executor asyncExcelServiceExecutor() {
    ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
    executor.setCorePoolSize(corePoolSize);
    executor.setMaxPoolSize(maxPoolSize);
    executor.setKeepAliveSeconds(keepAliveSeconds);
    //对拒绝task的处理策略
    executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
    executor.initialize();
    return executor;
  }
}

3、启动类上增加启动线程注解

@EnableAsync
@EnableConfigurationProperties({ExcutorConfig .class} ) // 开启配置属性支持

4、接下来是调用线程执行任务

 @Async("taskExecutor") 
    public Future<> doTask(int i) throws Exception{
        logger.info("执行线程任务!!");
        return new AsyncResult<>()
    }

5、调用异步执行,返回一个Future对象,.get()拿到实际获取到的对象。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值