44 lines
1.4 KiB
Java
44 lines
1.4 KiB
Java
package top.r3944realms.docchecktoolrefactored;
|
|
|
|
import java.util.Map;
|
|
import java.util.concurrent.*;
|
|
|
|
public class ThreadPoolManager {
|
|
private static final Map<String, ExecutorService> pools = new ConcurrentHashMap<>();
|
|
|
|
public static ExecutorService createPool(String name, int size) {
|
|
return createPool(name, size, true); // 默认使用守护线程
|
|
}
|
|
|
|
public static ExecutorService createPool(String name, int size, boolean daemon) {
|
|
ThreadFactory factory = daemon ?
|
|
r -> {
|
|
Thread t = new Thread(r, name + "-thread");
|
|
t.setDaemon(true);
|
|
return t;
|
|
} :
|
|
r -> new Thread(r, name + "-thread");
|
|
|
|
ExecutorService pool = Executors.newFixedThreadPool(size, factory);
|
|
pools.put(name, pool);
|
|
return pool;
|
|
}
|
|
|
|
public static void shutdownAll() {
|
|
pools.forEach((name, pool) -> {
|
|
if (!pool.isShutdown()) {
|
|
try {
|
|
pool.shutdown();
|
|
if (!pool.awaitTermination(5, TimeUnit.SECONDS)) {
|
|
pool.shutdownNow();
|
|
}
|
|
} catch (InterruptedException e) {
|
|
pool.shutdownNow();
|
|
Thread.currentThread().interrupt();
|
|
}
|
|
}
|
|
});
|
|
pools.clear();
|
|
}
|
|
}
|