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 ;
    }

}

使用方法

	//注入
    @Resource
	private TreadPoolConfig treadPoolConfig;
   //调用 
   public void test() {
		treadPoolConfig.buildHttpApiThreadPool().execute(()->System.out.println("tre"));
	}

 

现在两种线程池的创建方法已经介绍完了

 

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值