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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM