溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

springboot如何創建線程池

發布時間:2021-12-29 12:38:36 來源:億速云 閱讀:241 作者:小新 欄目:開發技術

這篇文章主要介紹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 ;
 } 
}

使用方法

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

現在兩種線程池的創建方法已經介紹完了。

springboot開啟線程池

定義線程池

定義的位置,要在啟動類的子包或者同級目錄中

import lombok.Data;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.ThreadPoolExecutor;
@Data
@Configuration
@EnableAsync //開啟異步請求
public class ThreadPoolConfig {
  
    private static final int corePoolSize = 10;   // 核心線程數(默認線程數)
    private static final int maxPoolSize = 100;   // 最大線程數
    private static final int keepAliveTime = 10;  // 允許線程空閑時間(單位:默認為秒)
    private static final int queueCapacity = 500; // 緩沖隊列數
    /**
     * 默認異步線程池
     * @return
     */
    @Bean("taskExecutor")
    public ThreadPoolTaskExecutor taskExecutor(){
        ThreadPoolTaskExecutor pool = new ThreadPoolTaskExecutor();
        pool.setThreadNamePrefix("--------------全局線程池-----------------");
        pool.setCorePoolSize(corePoolSize);
        pool.setMaxPoolSize(maxPoolSize);
        pool.setKeepAliveSeconds(keepAliveTime);
        pool.setQueueCapacity(queueCapacity);
        // 直接在execute方法的調用線程中運行
        pool.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        // 初始化
        pool.initialize();
        return pool;
    }
}

使用

直接在需要異步執行的方法上加注解

@Async("taskExecutor")

以上是“springboot如何創建線程池”這篇文章的所有內容,感謝各位的閱讀!希望分享的內容對大家有幫助,更多相關知識,歡迎關注億速云行業資訊頻道!

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女