美文网首页
ThreadPoolTaskExecutor

ThreadPoolTaskExecutor

作者: Jasyl | 来源:发表于2019-10-10 08:52 被阅读0次

    ThreadPoolTaskExecutor是什么

    • 类名org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor
      从类名可以看出这是spring的线程池

    • 再来看下init方法,其实底层就是ThreadPoolExecutor

        @Override
        protected ExecutorService initializeExecutor(
                ThreadFactory threadFactory, RejectedExecutionHandler rejectedExecutionHandler) {
    
            BlockingQueue<Runnable> queue = createQueue(this.queueCapacity);
            ThreadPoolExecutor executor  = new ThreadPoolExecutor(
                    this.corePoolSize, this.maxPoolSize, this.keepAliveSeconds, TimeUnit.SECONDS,
                    queue, threadFactory, rejectedExecutionHandler);
            if (this.allowCoreThreadTimeOut) {
                executor.allowCoreThreadTimeOut(true);
            }
    
            this.threadPoolExecutor = executor;
            return executor;
        }
    

    ThreadPoolTaskExecutor解决什么问题

    • ThreadPoolTaskExecutor是InitializingBean、DisposableBean的实现类,
      spring容器后会自动处理其初始化方法和注销方法,我们只需配置bean即可
    • 线程池的单例问题,交给spring容器实现单例,不用自己实现单例

    ThreadPoolTaskExecutor简介和用法

        @Bean
        public ThreadPoolTaskExecutor myTaskExecutor() {
            ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
            // 核心线程数
            taskExecutor.setCorePoolSize(5);
            // 最大线程数
            taskExecutor.setMaxPoolSize(15);
            // 队列大小 默认使用LinkedBlockingQueue
            taskExecutor.setQueueCapacity(100);
            // 线程最大空闲时间
            taskExecutor.setKeepAliveSeconds(300);
            // 拒绝策略 默认new ThreadPoolExecutor.AbortPolicy()
            taskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
            // 线程名称前缀
            taskExecutor.setThreadNamePrefix("My-Task-Executor-");
            //交给spring托管的会自动初始化,因为实现了InitializingBean接口
            //taskExecutor.initialize();
            return taskExecutor;
        }
    
        @Autowired
        private ThreadPoolTaskExecutor myTaskExecutor;
    
        public void sendMsg() {
            myTaskExecutor.execute(new Runnable() {
                @Override
                public void run() {
                    System.out.println("发送消息");
                }
            });
        }
    

    相关文章

      网友评论

          本文标题:ThreadPoolTaskExecutor

          本文链接:https://www.haomeiwen.com/subject/qkwzuctx.html