import org.apache.commons.lang3.concurrent.BasicThreadFactory;
import org.springframework.stereotype.Component;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
@Component
public class ThreadConfig {
private static volatile ThreadPoolExecutor threadPoolExecutor = null;
// 线程池的核心线程数
private static final int CORE_POOL_SIZE = 0;
// 线程大容量
private static final int MAX_NUM_POOL_SZIE = 1000;
// 非核心线程存活时间
private static final long KEEP_ALIVE_TIME = 2;
private static final TimeUnit UNIT = TimeUnit.MINUTES;
private static final int CAPACITY = 20;
// 拒绝策略 当线程数量达到非核心线程数, 并且队列中的等待的任务也满了, 那么则执行拒绝策略
private static final RejectedExecutionHandler HANDLER = new ThreadPoolExecutor.CallerRunsPolicy();
private static final BasicThreadFactory factory =
new BasicThreadFactory.Builder().namingPattern("commont-util-thread-pool-%d").build();
public static ThreadPoolExecutor getInstance() {
if (threadPoolExecutor == null) {
synchronized (ThreadPoolFactory.class) {
if (threadPoolExecutor == null) {
threadPoolExecutor = new ThreadPoolExecutor(CORE_POOL_SIZE, MAX_NUM_POOL_SZIE, KEEP_ALIVE_TIME, UNIT,
new ArrayBlockingQueue<>(CAPACITY), factory, HANDLER);
}
}
}
return threadPoolExecutor;
}
}
|