SpringBoot执行多线程

1.新建配置类,配置线程池

@Configuration
@EnableAsync
public class ThreadPoolConfiguration {

    @Bean("ThreadPools")
    public Executor doSomethingExecutor() {
        ThreadPoolTaskExecutor pool= new ThreadPoolTaskExecutor();
        // 核心线程数,线程池创建时候初始化的线程数
        pool.setCorePoolSize(10);
        // 最大线程数,线程池最大的线程数,只有在缓冲队列满了之后才会申请超过核心线程数的线程
        pool.setMaxPoolSize(20);
        // 缓冲队列,用来缓冲执行任务的队列
        pool.setQueueCapacity(500);
        // 允许线程的空闲时间,当超过了核心线程之外的线程在空闲时间到达之后会被销毁
        pool.setKeepAliveSeconds(60);
        // 线程池名的前缀
        pool.setThreadNamePrefix("Thread-");
        // 缓冲队列满了之后的拒绝策略,由调用线程处理(一般是主线程)
        pool.setRejectedExecutionHandler(new ThreadPoolExecutor.DiscardPolicy());
        pool.initialize();
        return pool;
    }
}

2.在被执行的方法上加上 @Async  注解并指定线程池

@Service
@Slf4j
public class CeService{

    @Async("ThreadPools")
    public void ce(){
        log.info("开始了");
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            log.error("error:", e);
        }
    }

​​​​​​​}

3.使用

@RestController
@Slf4j
public class index {
    @Autowired
    private CeService ceService;

    @GetMapping("/index")
    public String index(){
        int count = 100;
        for (int i = 0; i < count; i++) {
            ceService.ce();
        }
        return "success";
    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值