记手动粗浅管理多线程的工具类
首先新建一个线程池管理工具类ThreadPoolManagerUtil
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
/**
* 线程池管理工具类
* 提供多实例线程池的管理功能,支持动态配置、线程池状态监控、优雅关闭等操作。
*/
@Slf4j
public class ThreadPoolManagerUtil {
/**
* 多线程池实例集合
*/
private static final ConcurrentHashMap<String, ThreadPoolExecutor> threadPools = new ConcurrentHashMap<>();
private static final ConcurrentHashMap<String, Long> lastAccessTimeMap = new ConcurrentHashMap<>();
/**
* 定时清理任务
*/
private static final ScheduledExecutorService cleanerExecutor = new ScheduledThreadPoolExecutor(1, createCustomThreadFactory("ThreadPoolCleaner"));
/**
* 核心线程数:线程池中保持活跃的基本线程数量。
*/
private static final int DEFAULT_CORE_POOL_SIZE = 8;
/**
* 最大线程数:线程池允许的最大线程数量。
*/
private static final int DEFAULT_MAXIMUM_POOL_SIZE = 16;
/**
* 线程空闲存活时间:当线程数超过核心线程数时,多余线程的空闲存活时间。
*/
private static final long DEFAULT_KEEP_ALIVE_TIME = 60L;
/**
* 阻塞队列容量:用于存放等待执行任务的队列大小。
*/
private static final int DEFAULT_QUEUE_CAPACITY = 100;
/**
* 私有构造方法,避免外部实例化
*/
private ThreadPoolManagerUtil() {
}
/**
* 获取多实例线程池(通过名称区分)
*
* @param name 线程池名称
* @param corePoolSize 核心线程数
* @param maximumPoolSize 最大线程数
* @param keepAliveTime 空闲线程存活时间
* @param queueCapacity 阻塞队列容量
* @return 对应名称的线程池实例
*/
public static ThreadPoolExecutor getThreadPoolExecutor(String name, int corePoolSize, int maximumPoolSize, long keepAliveTime, int queueCapacity) {
threadPools.computeIfAbsent(name, k -> {
log.info("Initializing thread pool: {}", name);
return new ThreadPoolExecutor(
corePoolSize,
maximumPoolSize,
keepAliveTime,
TimeUnit.SECONDS,
new ArrayBlockingQueue<>(queueCapacity),
createCustomThreadFactory(name),
new ThreadPoolExecutor.CallerRunsPolicy()
);
});
lastAccessTimeMap.put(name, System.currentTimeMillis());
return threadPools.get(name);
}
/**
* 提供默认配置的多实例线程池
*
* @param name 线程池名称
* @return 对应名称的线程池实例
*/
public static ThreadPoolExecutor getThreadPoolExecutor(String name) {
return getThreadPoolExecutor(name, DEFAULT_CORE_POOL_SIZE, DEFAULT_MAXIMUM_POOL_SIZE, DEFAULT_KEEP_ALIVE_TIME, DEFAULT_QUEUE_CAPACITY);
}
/**
* 动态调整线程池参数
*
* @param name 线程池名称
* @param corePoolSize 核心线程数
* @param maximumPoolSize 最大线程数
* @param keepAliveTime 空闲线程存活时间
* @param unit 存活时间单位
*/
public static void adjustThreadPool(String name, int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit) {
ThreadPoolExecutor executor = threadPools.get(name);
if (executor != null) {
log.info("Adjusting thread pool: Name={}, CorePoolSize={}, MaximumPoolSize={}, KeepAliveTime={}",
name, corePoolSize, maximumPoolSize, keepAliveTime);
executor.setCorePoolSize(corePoolSize);
executor.setMaximumPoolSize(maximumPoolSize);
executor.setKeepAliveTime(keepAliveTime, unit);
} else {
log.warn("Thread pool [{}] does not exist, cannot adjust parameters.", name);
}
}
/**
* 移除并关闭指定名称的线程池
*
* @param name 线程池名称
*/
public static void removeThreadPool(String name) {
ThreadPoolExecutor executor = threadPools.remove(name);
if (executor != null && !executor.isShutdown()) {
log.info("Removing and shutting down thread pool: {}", name);
executor.shutdown();
try {
if (!executor.awaitTermination(60, TimeUnit.SECONDS)) {
executor.shutdownNow();
}
} catch (InterruptedException e) {
executor.shutdownNow();
Thread.currentThread().interrupt();
}
}
lastAccessTimeMap.remove(name);
}
/**
* 优雅关闭所有多实例线程池
*/
public static void shutdownAllThreadPools() {
log.info("Shutting down all thread pools...");
threadPools.forEach((name, executor) -> {
if (!executor.isShutdown()) {
log.info("Shutting down thread pool: {}", name);
executor.shutdown();
try {
if (!executor.awaitTermination(60, TimeUnit.SECONDS)) {
executor.shutdownNow();
}
} catch (InterruptedException e) {
executor.shutdownNow();
Thread.currentThread().interrupt();
}
}
});
threadPools.clear();
lastAccessTimeMap.clear();
}
/**
* 自定义线程工厂,支持线程命名和守护线程
*
* @param threadNamePrefix 线程名前缀
* @return 自定义线程工厂
*/
private static ThreadFactory createCustomThreadFactory(String threadNamePrefix) {
return new ThreadFactory() {
private final AtomicInteger threadNumber = new AtomicInteger(1);
@Override
public Thread newThread(@NotNull Runnable r) {
Thread thread = new Thread(r, threadNamePrefix + "-thread-" + threadNumber.getAndIncrement());
// 设置为守护线程
thread.setDaemon(true);
return thread;
}
};
}
/**
* 获取线程池状态信息
*
* @param executor 线程池实例
* @return 线程池状态信息
*/
public static String getThreadPoolStatus(ThreadPoolExecutor executor) {
return String.format("ThreadPool Status: [CorePoolSize: %d, MaximumPoolSize: %d, ActiveCount: %d, QueueSize: %d, CompletedTaskCount: %d]",
executor.getCorePoolSize(),
executor.getMaximumPoolSize(),
executor.getActiveCount(),
executor.getQueue().size(),
executor.getCompletedTaskCount());
}
/*
定时清理逻辑
*/
static {
cleanerExecutor.scheduleAtFixedRate(() -> {
long now = System.currentTimeMillis();
threadPools.forEach((name, executor) -> {
Long lastAccessTime = lastAccessTimeMap.get(name);
if (lastAccessTime != null && (now - lastAccessTime > TimeUnit.MINUTES.toMillis(10))) {
log.info("Removing inactive thread pool: {}", name);
executor.shutdown();
try {
if (!executor.awaitTermination(60, TimeUnit.SECONDS)) {
executor.shutdownNow();
}
} catch (InterruptedException e) {
executor.shutdownNow();
Thread.currentThread().interrupt();
}
threadPools.remove(name);
lastAccessTimeMap.remove(name);
}
});
}, 10, 10, TimeUnit.MINUTES);
}
}
简易使用示例
public static void main(String[] args) {
List<String> list = new ArrayList<>();
// 获取线程池
ThreadPoolExecutor threadPool = ThreadPoolManagerUtil.getThreadPoolExecutor("groupResources");
// 线程同步执行
list.parallelStream().forEach(vo ->
threadPool.execute(() -> {
try {
// todo 业务逻辑处理
} catch (Exception ex) {
log.error("", ex);
}
}));
// 线程异步执行
List<CompletableFuture<Void>> futures = list.parallelStream().map(vo -> CompletableFuture.runAsync(() -> {
try {
// todo 业务逻辑处理
} catch (Exception ex) {
log.error("", ex);
}
}, threadPool)
).toList();
// 等待当前批次完成
CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).join();
// 根据需要关闭线程池
threadPool.shutdown();
}

浙公网安备 33010602011771号