java 线程池通过 allowcorethreadtimeout 参数配合 keepalivetime 实现空闲时间回收线程。默认情况下,核心线程不会因空闲而终止,只有非核心线程在超过存活时间后才会被回收。若需让核心线程也参与回收,调用 setallowcorethreadtimeout(true) 即可,此时所有线程均受 keepalivetime 控制。

ThreadPoolExecutor 中核心线程何时被回收
核心线程默认不回收,必须显式开启超时设置才会被销毁。当线程池处于空闲状态且无新任务提交时,若已启用核心线程超时,核心线程会在等待队列取任务超时后被终止。此行为由 getTask() 方法中的逻辑驱动,判断条件包括是否允许核心线程超时及当前线程数是否超过核心线程数限制。

import java.util.concurrent.*;
public class CoreThreadTimeoutDemo {
public static void main(String[] args) throws InterruptedException {
ThreadPoolExecutor executor = new ThreadPoolExecutor(
2, // corePoolSize
4, // maximumPoolSize
60L, TimeUnit.SECONDS, // keepAliveTime
new LinkedBlockingQueue<>(),
Executors.defaultThreadFactory()
);
// 允许核心线程超时
executor.allowCoreThreadTimeOut(true);
System.out.println("Before task: active=" + executor.getActiveCount() + ", poolSize=" + executor.getPoolSize());
// 提交一个任务并立即退出main,观察线程回收
executor.submit(() -> {
System.out.println("Task running on thread: " + Thread.currentThread().getName());
});
// 等待任务执行完毕
Thread.sleep(1000);
System.out.println("After task: active=" + executor.getActiveCount() + ", poolSize=" + executor.getPoolSize());
// 关闭线程池
executor.shutdown();
}
}
预期输出:
Before task: active=0, poolSize=0
Task running on thread: pool-1-thread-1
After task: active=0, poolSize=0
立即学习“Java免费学习笔记(深入)”;
上述代码中,allowCoreThreadTimeOut(true) 是关键设置。未设置前,即使线程池空闲,核心线程仍会保留;设置后,核心线程在 keepAliveTime 时间内未获取到任务将被终止。注意:若队列未满且线程数小于核心线程数,新任务会优先创建核心线程而非复用空闲线程,除非已启用超时机制。
在代码库出现结构漂移之前,扫描JS或TS代码库中的禁止导入、循环依赖、孤立模块和其他依赖规则违规情况。
非核心线程与核心线程回收行为的差异对比
非核心线程在空闲超过 keepAliveTime 后自动回收,无需额外配置;核心线程则需手动开启超时开关才能被回收。两者在任务调度、资源占用和响应延迟上存在显著差异。非核心线程适用于突发流量场景,核心线程适合长期稳定负载。正确选择策略可避免资源浪费或响应迟缓。

import java.util.concurrent.*;
public class NonCoreVsCoreRecycleDemo {
public static void main(String[] args) throws InterruptedException {
// 场景1:非核心线程回收(默认行为)
ThreadPoolExecutor exec1 = new ThreadPoolExecutor(
1, 2, 5L, TimeUnit.SECONDS,
new LinkedBlockingQueue<>(),
Executors.defaultThreadFactory()
);
// 场景2:核心线程回收(需开启allowCoreThreadTimeOut)
ThreadPoolExecutor exec2 = new ThreadPoolExecutor(
1, 2, 5L, TimeUnit.SECONDS,
new LinkedBlockingQueue<>(),
Executors.defaultThreadFactory()
);
exec2.allowCoreThreadTimeOut(true);
System.out.println("--- Scenario 1: Non-core thread recycle ---");
exec1.submit(() -> { /* do nothing */ });
Thread.sleep(6000); // 超过keepAliveTime
System.out.println("Exec1 pool size after idle: " + exec1.getPoolSize());
exec1.shutdown();
System.out.println("--- Scenario 2: Core thread recycle ---");
exec2.submit(() -> { /* do nothing */ });
Thread.sleep(6000); // 超过keepAliveTime
System.out.println("Exec2 pool size after idle: " + exec2.getPoolSize());
exec2.shutdown();
}
}
预期输出:
--- Scenario 1: Non-core thread recycle ---
Exec1 pool size after idle: 1
--- Scenario 2: Core thread recycle ---
Exec2 pool size after idle: 0
在场景1中,虽然提交了任务,但线程数为1(等于corePoolSize),因此该线程被视为核心线程,不会因空闲而回收(因为未开启allowCoreThreadTimeOut)。在场景2中,同样提交任务,但由于开启了allowCoreThreadTimeOut,核心线程在空闲5秒后被回收,poolSize降为0。这证明:仅当allowCoreThreadTimeOut为true时,核心线程才会像非核心线程一样被回收。否则,核心线程将永久驻留,直到线程池被关闭。
当线程池空闲且无任务时,实际运行的线程数量是多少
当线程池空闲且无任务时,实际运行的线程数量取决于是否启用了核心线程超时以及当前线程数是否超过核心线程数。若未启用核心线程超时,核心线程将保持活跃状态,即使无任务也在运行(阻塞于take());若已启用,则核心线程会在超时后被终止,最终线程数为0。非核心线程在无任务且超时后也会被终止。因此,最终线程数可能为0或corePoolSize,具体由allowCoreThreadTimeOut决定。

















