線程池

@Component
public class ThreadConfig {

    private static ThreadPoolExecutor threadPoolExecutor=null;

    private static final int CORE_POOL_SIZE = 8; //核心線程數
    private static final int MAX_POOL_SIZE = 38; //最大線程數
    private static final int QUEUE_CAPACITY = 100;
    private static final Long KEEP_ALIVE_TIME = 1L; //等待時間爲 1L

    //CallerRunsPolicy()策略 :調用執行自己的線程運行任務。您不會任務請求。
    // 但是這種策略會降低對於新任務提交速度,影響程序的整體性能。另外,這個策略喜歡增加隊列容量。
    // 如果您的應用程序可以承受此延遲並且你不能任務丟棄任何一個任務請求的話,你可以選擇這個策略。
    @Bean
    public ThreadPoolExecutor poolExecutor(){
        if(null==threadPoolExecutor){
         return  new ThreadPoolExecutor(
                    CORE_POOL_SIZE,
                    MAX_POOL_SIZE,
                    KEEP_ALIVE_TIME,
                    TimeUnit.SECONDS,  //等待時間的單位
                    new ArrayBlockingQueue<>(QUEUE_CAPACITY),
                    new ThreadPoolExecutor.CallerRunsPolicy());
        }else {
            return threadPoolExecutor;
        }
    }
}

 

發佈了75 篇原創文章 · 獲贊 23 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章