欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Spring Boot线程池ThreadPoolTaskExecutor

程序员文章站 2022-05-01 13:04:11
...

ThreadPoolTaskExecutor是一个spring的线程池技术,它内部属性使用的是jdk中的java.util.concurrent.ThreadPoolExecutor进行实现,等同于ThreadPoolExecutor创建的线程池。

ThreadPoolTaskExecutor的参数:
  int corePoolSize:线程池维护线程的最小数量. 
  int maximumPoolSize:线程池维护线程的最大数量. 
  long keepAliveTime:空闲线程的存活时间. 
  TimeUnit unit: 时间单位,现有纳秒,微秒,毫秒,秒枚举值. 
  BlockingQueue<Runnable> workQueue:持有等待执行的任务队列. 
  RejectedExecutionHandler handler: 用来拒绝一个任务的执行,有两种情况会发生这种情况。 
  一是在execute方法中若addIfUnderMaximumPoolSize(command)为false,即线程池已经饱和; 
  二是在execute方法中, 发现runState!=RUNNING || poolSize == 0,即已经shutdown,就调用ensureQueuedTaskHandled(Runnable command),在该方法中有可能调用reject。

Spring Boot自定义线程池

package com.boot.admin.thread;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

@Configuration
@EnableAsync //开启异步任务支持 
public class ThreadPoolConfig implements AsyncConfigurer {

	private static final int CORE_POLL_SIZE = 150;
	
	private static final int MAX_POLL_SIZE = 200;
	
	private static final int QUEUE_CAPACITY = 1000000;
	
	private static final int KEEP_ALIVE_SECONDS = 60;
	
	/**
	 * 实现AsyncConfigurer接口并重写getAsyncExecutor方法,
	 * 创建线程池ThreadPoolTaskExecutor(Spring自带的线程池与Java使用的还是有些区分),并返回
	 */
	@Override
	public Executor getAsyncExecutor() {
		 ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
         taskExecutor.setCorePoolSize(CORE_POLL_SIZE);//核心线程数
         taskExecutor.setMaxPoolSize(MAX_POLL_SIZE);//最大线程数
         taskExecutor.setQueueCapacity(QUEUE_CAPACITY);//队列最大长度
         taskExecutor.setKeepAliveSeconds(KEEP_ALIVE_SECONDS);//线程池维护线程所允许的空闲时间
         taskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());//线程池对拒绝任务(无线程可用)的处理策略
         taskExecutor.initialize();
         return taskExecutor;
	}

	@Override
	public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
		// TODO Auto-generated method stub
		return null;
	}

}
Reject策略预定义有四种: 
(1)ThreadPoolExecutor.AbortPolicy策略,是默认的策略,处理程序遭到拒绝将抛出运行时 RejectedExecutionException。 
(2)ThreadPoolExecutor.CallerRunsPolicy策略 ,调用者的线程会执行该任务,如果执行器已关闭,则丢弃. 
(3)ThreadPoolExecutor.DiscardPolicy策略,不能执行的任务将被丢弃. 
(4)ThreadPoolExecutor.DiscardOldestPolicy策略,如果执行程序尚未关闭,则位于工作队列头部的任务将被删除,然后重试执行程序(如果再次失败,则重复此过程).