您现在的位置是:主页 > Web前端技术 > Web前端技术
springboot如何创建线程池开发技术
IDCBT2021-12-30【服务器技术】人已围观
简介这篇文章主要介绍springboot如何创建线程池,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完! springboot创建线程池两种方式1.使用static代码块创建 这样的方式
这篇文章主要介绍springboot如何创建线程池,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!
springboot创建线程池两种方式1.使用static代码块创建这样的方式创建的好处是当代码用到线程池的时候才会初始化核心线程数
具体代码如下:
public class HttpApiThreadPool { /** 获取当前系统的CPU 数目*/ static int cpuNums = Runtime.getRuntime().availableProcessors(); /** 线程池核心池的大小*/ private static int corePoolSize = 10; /** 线程池的最大线程数*/ private static int maximumPoolSize = cpuNums * 5; public static ExecutorService httpApiThreadPool = null; /** * 静态方法 */ static{ System.out.println("创建线程数:"+corePoolSize+",最大线程数:"+maximumPoolSize); //建立10个核心线程,线程请求个数超过20,则进入队列等待 httpApiThreadPool = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, 0L, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<Runnable>(100),new ThreadFactoryBuilder().setNameFormat("PROS-%d").build()); } }
使用方法
public static void main(String[] args) { HttpApiThreadPool.httpApiThreadPool.execute(()->System.out.println("测试")); }
注意:
1.不能使用Executors的方法创建线程池,这个是大量的生产事故得出来的结论
2.maximumPoolSize本程序使用的是cup数的5倍,你可以看你实际情况用
3.new ThreadFactoryBuilder().setNameFormat("PROS-%d").build() 给每个线程已名字,可以方便调试
2.使用@Configuration @bean注解,程序启动时创建@Configuration public class TreadPoolConfig { private Logger logger = LoggerFactory.getLogger(TreadPoolConfig.class); /** 获取当前系统的CPU 数目*/ int cpuNums = Runtime.getRuntime().availableProcessors(); /** 线程池核心池的大小*/ private int corePoolSize = 10; /** 线程池的最大线程数*/ private int maximumPoolSize = cpuNums * 5; /** * 消费队列线程 * @return */ @Bean(value = "httpApiThreadPool") public ExecutorService buildHttpApiThreadPool(){ logger.info("TreadPoolConfig创建线程数:"+corePoolSize+",最大线程数:"+maximumPoolSize); ExecutorService pool = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, 0L, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<Runnable>(100),new ThreadFactoryBuilder().setNameFormat("PROS-%d").build()); return pool ; } }标签:很赞哦! ()