ThreadPoolTaskExecutor創建線程池


1.前言

ThreadPoolTaskExecutor和ThreadPoolExecutor什么關系?

ThreadPoolTaskExecutor是spring core包中的,而ThreadPoolExecutor是JDK中的JUC(java.util .concurrent)
ThreadPoolTaskExecutor是對ThreadPoolExecutor進行了封裝處理。
來看一下ThreadPoolExecutor和ThreadPoolTaskExecutor結構,祖類都是調用Executor接口:


下面是ThreadPoolTaskExecutor 中的部分源碼,就使用到了ThreadPoolExecutor 。

public class ThreadPoolTaskExecutor extends ExecutorConfigurationSupport implements AsyncListenableTaskExecutor, SchedulingTaskExecutor {
    private final Object poolSizeMonitor = new Object();
    private int corePoolSize = 1;
    private int maxPoolSize = 2147483647;
    private int keepAliveSeconds = 60;
    private int queueCapacity = 2147483647;
    private boolean allowCoreThreadTimeOut = false;
    @Nullable
    private TaskDecorator taskDecorator;
    @Nullable
    private ThreadPoolExecutor threadPoolExecutor;
    private final Map<Runnable, Object> decoratedTaskMap;

關於ThreadPoolExecutor中參數詳情看Executor的文章。

2.springboot配置使用

配置文件

@Configuration
@EnableAsync
public class SpringThreadPoolExecutorConfig {
 
    @Bean(name = "threadPoolTaskExecutor")
    public ThreadPoolTaskExecutor threadPoolTaskExecutor() {
        ThreadPoolTaskExecutor pool = new ThreadPoolTaskExecutor();
        pool.setKeepAliveSeconds(300);
        //核心線程池數
        pool.setCorePoolSize(50);
        //最大線程
        pool.setMaxPoolSize(100);
        //隊列容量
        pool.setQueueCapacity(1000);
        //隊列滿,線程被拒絕執行策略
        pool.setRejectedExecutionHandler(new java.util.concurrent.ThreadPoolExecutor.CallerRunsPolicy());
        pool.setThreadNamePrefix("aaaa-common-support-service--");
        return pool;
    }

Reject策略預定義有四種

  • ThreadPoolExecutor.AbortPolicy策略,是默認的策略,處理程序遭到拒絕將拋出運行時 RejectedExecutionException。

  • ThreadPoolExecutor.CallerRunsPolicy策略 ,調用者的線程會執行該任務,如果執行器已關閉,則丟棄.

  • ThreadPoolExecutor.DiscardPolicy策略,不能執行的任務將被丟棄.

  • ThreadPoolExecutor.DiscardOldestPolicy策略,如果執行程序尚未關閉,則位於工作隊列頭部的任務將被刪除,然后重試執行程序(如果再次失敗,則重復此過程).

使用

@Slf4j
@Service("AService")
public class AServiceImpl implements AService {
 
	@Autowired
	private ThreadPoolTaskExecutor threadPoolTaskExecutor;
 
	@Override
	public List<String> queryUserByGivenname(String txNo, String givenname)
			throws ParamInvalidException {	
			threadPoolTaskExecutor.execute(()->{
				log.info("-------txNO[{}],givename[{}]", txNo,givenname);
			});
		return null;
	}
}


免責聲明!

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



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