0
点赞
收藏
分享

微信扫一扫

springboot异步处理,自定义线程池

是波波呀 2022-03-12 阅读 38
  1. 线程池配置类
@Configuration
public class ThreadPoolConfig {

    @Bean("threadPoolTaskExecutor_1")
    public ThreadPoolTaskExecutor threadPoolTaskExecutor_1() {
        System.out.println("线程池threadPoolTaskExecutor1初始化===============>开始:"+ System.currentTimeMillis());
        ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();

        //配置线程池
        threadPoolTaskExecutor.setCorePoolSize(10);//核心线程数10:线程池创建时候初始化的线程数
        threadPoolTaskExecutor.setMaxPoolSize(30);//最大线程数30:线程池最大的线程数,只有在缓冲队列满了之后才会申请超过核心线程数的线程
        threadPoolTaskExecutor.setQueueCapacity(100);//缓冲队列100:用来缓冲执行任务的队列
        threadPoolTaskExecutor.setKeepAliveSeconds(60);//允许线程的空闲时间60秒:当超过了核心线程数之外的线程(上面设置10个),在空闲时间到达之后会被销毁
        threadPoolTaskExecutor.setThreadNamePrefix("threadPoolTaskExecutor1");//线程池名的前缀:方便我们定位处理任务所在的线程池
        threadPoolTaskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());//线程池对拒绝任务的处理策略:这里采用了CallerRunsPolicy策略,当线程池没有处理能力的时候,该策略会直接在execute方法的调用线程中运行被拒绝的任务;如果执行程序已关闭,则会丢弃该任务
        threadPoolTaskExecutor.setWaitForTasksToCompleteOnShutdown(true);//关闭线程池的时候,是否等待当前任务执行完成
        threadPoolTaskExecutor.setAwaitTerminationSeconds(60);//等待当前任务完成的超时时间60秒,如果一直等待就会造成阻塞

        //初始化线程池
        threadPoolTaskExecutor.initialize();
        System.out.println("线程池threadPoolTaskExecutor1初始化===============>完成:"+ System.currentTimeMillis());
        return threadPoolTaskExecutor;
    }

}
  1. 使用线程
public class ThreadPoolTest {

    @Async("threadPoolTaskExecutor_1")
    public void test01() {
        try {
            Thread.sleep(5000);
            System.out.println("test01当前线程是{}" + Thread.currentThread().getName());
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    
}
举报

相关推荐

0 条评论