zoukankan      html  css  js  c++  java
  • SpringBoot配置ThreadPoolTaskExecutor

    package com.example.demo;
    
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
    
    import java.util.concurrent.Executor;
    import java.util.concurrent.ThreadPoolExecutor;
    
    /**
     * 1. 当一个任务被提交到线程池时,首先查看线程池的核心线程是否都在执行任务,否就选择一条线程执行任务,是就执行第二步。
     * 2. 查看核心线程池是否已满,不满就创建一条线程执行任务,否则执行第三步。
     * 3. 查看任务队列是否已满,不满就将任务存储在任务队列中(SynchronousQueue同步队直接执行第四步),否则执行第四步。
     * 4. 查看线程池是否已满,不满就创建一条线程执行任务,否则就按照策略处理无法执行的任务。
     */
    @Configuration
    public class ThreadPoolTaskConfig {
    
        @Bean
        public Executor executor(){
            ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
            //此方法返回可用处理器的虚拟机的最大数量; 不小于1
            int core = Runtime.getRuntime().availableProcessors();
            executor.setCorePoolSize(core);//设置核心线程数
            executor.setMaxPoolSize(core*2 + 1);//设置最大线程数
            executor.setKeepAliveSeconds(3);//除核心线程外的线程存活时间
            executor.setQueueCapacity(40);//如果传入值大于0,底层队列使用的是LinkedBlockingQueue,否则默认使用SynchronousQueue
            executor.setThreadNamePrefix("thread-execute");//线程名称前缀
            executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());//设置拒绝策略
            return executor;
        }
    }
    

    如上述代码已经配置好ThreadPoolTaskExecutor,在spring容器启动的时候会被初始化成bean存放在上下文中。需要使用的话只需要@autowired注入即可。
    ThreadPoolTaskExecutor底层调用的就是ThreadPoolExecuter,关于Lee老爷子的线程池原理可以参考之前的一篇博文
    https://blog.csdn.net/weixin_43142697/article/details/82875437

  • 相关阅读:
    【带权并查集】How Many Answers Are Wrong HDU
    【带权并查集+离散化】Parity game POJ
    【并查集】Supermarket POJ
    【并查集】P3958 奶酪
    【并查集-判环】Is It A Tree? POJ
    【最短路/线性差分约束】Layout POJ
    【最短路-负环】Extended Traffic LightOJ
    【最短路】Subway POJ
    【最短路-判负环 Floyd】Wormholes POJ
    [JZOJ]1293.气象牛[区间DP]
  • 原文地址:https://www.cnblogs.com/jtlgb/p/11796710.html
Copyright © 2011-2022 走看看