【线程池】快速上手SpringBoot多线程案例

1.启动类添加注解

@EnableScheduling

2.进行线程池config配置

//允许使用异步方法
@EnableAsync
@Configuration
public class ExecutorCreated {
    @Bean("tread")
    public Executor createdExecutor(){
        //创建线程池任务执行器对象
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        //配置程池线中核心线程数量
        executor.setCorePoolSize(10);
        //配置线程池中最大线程数量
        executor.setMaxPoolSize(100);
        //配置队列的长度
        executor.setQueueCapacity(200);
        //配置线程名称前缀
        executor.setThreadNamePrefix("executor");
        //配置拒绝策略,在任务被拒绝添加后会调用当前线程池的所在的线程去执行被拒绝的任务
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        //实例化执行者
        executor.initialize();
        return executor;
    }
}

3.创建需要在多线程环境中运行的Service方法

@Service
public class HelloService {
    //使用异步方法
    @Async("tread")
    public void hello(){
        DateFormat df =new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            Thread.sleep(5000);
            System.out.println("执行方法的线程: "+Thread.currentThread().getName());
            System.out.println("执行时间: "+df.format(new Date()));
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
}

4.在controller层进行调用执行访问

    @GetMapping("hello")
    public void hello(){
        helloService.hello();
    }

5.输出结果

总结:

我这边的service方法中添加了5秒延迟,在快速多次发送请求后发现并没有出现等待现象,而是不同的线程在异步的执行任务,线程池使用成功!

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值