单例线程池工具类
package com.xyhsoft.datagather.util;
import cn.hutool.core.thread.ThreadFactoryBuilder;
import lombok.extern.slf4j.Slf4j;
import java.util.concurrent.*;
@Slf4j
public class ThreadPoolUtil {
private static volatile ThreadPoolUtil INSTANCE;
public static ThreadPoolExecutor threadPoolExecutor;
private static final ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor();
private ThreadPoolUtil() {
int corePoolSize = Runtime.getRuntime().availableProcessors();
int maximumPoolSize = corePoolSize * 2;
BlockingQueue<Runnable> workQueue = new LinkedBlockingQueue<>(1);
ThreadFactory threadFactory = new ThreadFactoryBuilder()
.setNamePrefix("common-thread-pool")
.setDaemon(true)
.build();
RejectedExecutionHandler rejectedExecutionHandler = new ThreadPoolExecutor.AbortPolicy();
threadPoolExecutor = new ThreadPoolExecutor(
corePoolSize,
maximumPoolSize,
90L,
TimeUnit.SECONDS,
workQueue,
threadFactory,
(runnable, executor) -> {
if (!executor.isShutdown()) {
log.warn("任务:" + runnable.toString() + "已经被拒绝");
log.warn("正在尝试手动执行任务");
try {
singleThreadExecutor.submit(runnable);
} catch (Throwable throwable) {
log.error("手动执行任务异常:{},{}", runnable, throwable.getMessage());
}
}
});
}
public static ThreadPoolUtil getInstance() {
if (INSTANCE == null) {
synchronized (ThreadPoolUtil.class) {
if (INSTANCE == null) {
INSTANCE = new ThreadPoolUtil();
}
}
}
return INSTANCE;
}
public static void shutdownThreadPool() {
threadPoolExecutor.shutdown();
try {
if (!threadPoolExecutor.awaitTermination(60, TimeUnit.SECONDS)) {
threadPoolExecutor.shutdownNow();
}
} catch (InterruptedException ie) {
threadPoolExecutor.shutdownNow();
Thread.currentThread().interrupt();
}
}
public boolean isShutdown() {
return threadPoolExecutor.isShutdown();
}
public synchronized void restartThreadPool() {
if (threadPoolExecutor != null && !threadPoolExecutor.isShutdown()) {
threadPoolExecutor.shutdownNow();
try {
if (!threadPoolExecutor.awaitTermination(5, TimeUnit.SECONDS)) {
System.out.println("Warning: Not all tasks completed before the restart.");
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
threadPoolExecutor = createThreadPool();
}
private ThreadPoolExecutor createThreadPool() {
int corePoolSize = Runtime.getRuntime().availableProcessors();
int maxPoolSize = corePoolSize * 2;
BlockingQueue<Runnable> workQueue = new LinkedBlockingQueue<>();
ThreadFactory threadFactory = new ThreadFactoryBuilder().setNamePrefix("datagather-common-threadpool").build();
RejectedExecutionHandler handler = new ThreadPoolExecutor.CallerRunsPolicy();
return new ThreadPoolExecutor(corePoolSize, maxPoolSize, 60L, TimeUnit.SECONDS, workQueue, threadFactory, handler);
}
}