多线程ThreadPoolTaskExecutor的简单使用

基于springboot,当使用某方法时默认调用线程池

启动类

@SpringBootApplication
public class SpringBootApplication {
    public static void main(String[] args) {
        SpringApplication.run(SpringBootApplication .class,args);
    }
}

配置线程池类,注意不要忘记注解

@Configuration
@EnableAsync
public class ExecutorConfig {

    private static final int corePoolSize = 2;   // 核心线程数(默认线程数)
    private static final int maxPoolSize = 10;   // 最大线程数
    private static final int keepAliveTime = 2;  // 允许线程空闲时间(单位:默认为秒)
    private static final int queueCapacity = 20; // 缓冲队列数

    /**
     * 默认异步线程池
     * @return
     */
    @Bean("taskExecutor")
    public ThreadPoolTaskExecutor taskExecutor(){
        ThreadPoolTaskExecutor pool = new ThreadPoolTaskExecutor();
        pool.setThreadNamePrefix("--------------全局线程池-----------------");
        pool.setCorePoolSize(corePoolSize);
        pool.setMaxPoolSize(maxPoolSize);
        pool.setKeepAliveSeconds(keepAliveTime);
        pool.setQueueCapacity(queueCapacity);
        // 直接在execute方法的调用线程中运行
        pool.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        // 初始化
        pool.initialize();
        return pool;
    }
}

 需要被多线程调用的方法,需要加注解@async

@Component
public class Thread01 {

    @Async("taskExecutor")
    public void eat(){
        System.out.println(Thread.currentThread().getName()+"线程开吃");
    }
}

 测试类

@RunWith(SpringRunner.class)
@SpringBootTest
public class test {
    @Autowired
    Thread01 thread01;

    @Test
    public void test() {
        System.out.println(Thread.currentThread().getName()+"主线程开吃");
            thread01.eat();
            thread01.eat();
            
    }
}

输出结果 

main主线程开吃
--------------全局线程池-----------------1线程开吃
--------------全局线程池-----------------2线程开吃

可知 当调用这个方法时已启用线程池中的线程 就是如此简单

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值