以下是Java实现具有自动扩容与收缩机制的线程池方案,包含核心线程自动回收和动态扩容功能:
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
public class AutoScaleThreadPool {
private final ThreadPoolExecutor executor;
private final ScheduledExecutorService monitor;
private final int maxIdleTime;
public AutoScaleThreadPool(int coreSize, int maxSize,
int queueSize, int idleTimeSec) {
this.maxIdleTime = idleTimeSec * 1000;
this.executor = new ThreadPoolExecutor(
coreSize, maxSize,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<>(queueSize),
new ScaleThreadFactory());
this.monitor = Executors.newSingleThreadScheduledExecutor();
this.monitor.scheduleAtFixedRate(
this::adjustPoolSize, 5, 5, TimeUnit.SECONDS);
}
private void adjustPoolSize() {
int activeCount = executor.getActiveCount();
int poolSize = executor.getPoolSize();
int coreSize = executor.getCorePoolSize();
// 扩容逻辑:活动线程超过当前核心数80%且队列有积压
if (activeCount > coreSize * 0.8
&& !executor.getQueue().isEmpty()) {
executor.setCorePoolSize(Math.min(
coreSize + 2, executor.getMaximumPoolSize()));
}
// 缩容逻辑:连续3次检测到空闲
if (poolSize > coreSize
&& activeCount < coreSize * 0.3) {
executor.setCorePoolSize(Math.max(
coreSize - 1, 1));
}
}
public void execute(Runnable task) {
executor.execute(task);
}
public void shutdown() {
executor.shutdown();
monitor.shutdown();
}
private class ScaleThreadFactory implements ThreadFactory {
private final AtomicInteger counter = new AtomicInteger(0);
@Override
public Thread newThread(Runnable r) {
Thread t = new Thread(r);
t.setName("ScaleThread-" + counter.incrementAndGet());
t.setDaemon(false);
return t;
}
}
}
class TestPool {
public static void main(String[] args) throws InterruptedException {
AutoScaleThreadPool pool = new AutoScaleThreadPool(
2, 10, 100, 30);
// 模拟突发流量
for (int i = 0; i < 50; i++) {
final int taskId = i;
pool.execute(() -> {
System.out.println(Thread.currentThread().getName()
+ " 执行任务 " + taskId);
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
});
Thread.sleep(100);
}
Thread.sleep(30000);
pool.shutdown();
}
}
该实现包含动态调整线程池核心大小的监控线程,当任务积压时自动扩容,空闲时自动收缩。测试用例模拟了突发流量场景,可通过观察线程名称变化验证扩容效果。