1.
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;
}
}
2.
import lombok.extern.slf4j.Slf4j;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.aop.interceptor.SimpleAsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.core.task.TaskExecutor;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;
/**
* 初始化线程池
*/
@Slf4j
public class ThreadPoolService implements AsyncConfigurer {
@Bean
public TaskExecutor toolsTaskExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
int poolSize = Runtime.getRuntime().availableProcessors();
// 设置核心线程数
executor.setCorePoolSize(poolSize);
// 设置最大线程数
executor.setMaxPoolSize(poolSize * 3);
// 设置队列容量
executor.setQueueCapacity(128);
// 设置线程活跃时间(秒)
executor.setKeepAliveSeconds(60);
// 设置默认线程名称
executor.setThreadNamePrefix("my-Thread:");
// 设置拒绝策略
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
// 等待所有任务结束后再关闭线程池
executor.setWaitForTasksToCompleteOnShutdown(true);
//初始化
executor.initialize();
return executor;
}
@Override
public Executor getAsyncExecutor() {
return toolsTaskExecutor();
}
@Override
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
return new SimpleAsyncUncaughtExceptionHandler();
}
}