Java线程池停止空闲线程是否有规则呢?
Java线程池中线程的数量超过核心线程的数量,且所有线程空闲,空闲时间超过keepAliveTime,会停止超过核心线程数量的线程,那么会保留哪些线程呢?是不是有规则呢?
测试代码:
ThreadPoolExecutor executor = new ThreadPoolExecutor(3, 5, 3, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(5));
int taskNum = 13;
for (int i = 0; i < taskNum; i++) {
final int finalI = i;
if (i == 10) {
System.out.println("执行过10个任务,开始空闲");
try {
TimeUnit.SECONDS.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("提交任务:" + (i + 1));
executor.submit(new Runnable() {
public void run() {
Integer taskNum = finalI + 1;
System.out.println("task: " + taskNum + ", " + Thread.currentThread().getName() + ", " + System.currentTimeMillis());
}
});
}
运行结果
提交任务:1
提交任务:2
提交任务:3
提交任务:4
提交任务:5
提交任务:6
提交任务:7
提交任务:8
提交任务:9
提交任务:10
执行过10个任务,开始空闲
task: 2, pool-1-thread-2, 1522134893596
task: 1, pool-1-thread-1, 1522134893596
task: 3, pool-1-thread-3, 1522134893596
task: 9, pool-1-thread-4, 1522134893596
task: 4, pool-1-thread-2, 1522134893596
task: 6, pool-1-thread-4, 1522134893596
task: 5, pool-1-thread-3, 1522134893596
task: 8, pool-1-thread-1, 1522134893596
task: 7, pool-1-thread-2, 1522134893596
task: 10, pool-1-thread-5, 1522134893596
提交任务:11
提交任务:12
提交任务:13
task: 11, pool-1-thread-6, 1522134903606
task: 13, pool-1-thread-8, 1522134903606
task: 12, pool-1-thread-7, 1522134903606
根据多次试验,发现每次保留作为核心线程的线程并没规律或规则。因此,线程池中线程数量达到最大允许的线程数量,然后所有线程都同时进入空闲状态且空闲时间超过keepAliveTime,停止多余的线程并保留核心数量的线程是没有规律或规则。

作者: Acode
出处: http://www.cnblogs.com/acode/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出, 原文链接 如有问题, 可留言咨询.
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 理解Rust引用及其生命周期标识(下)
· 从二进制到误差:逐行拆解C语言浮点运算中的4008175468544之谜
· .NET制作智能桌面机器人:结合BotSharp智能体框架开发语音交互
· 软件产品开发中常见的10个问题及处理方法
· .NET 原生驾驭 AI 新基建实战系列:向量数据库的应用与畅想
· 2025成都.NET开发者Connect圆满结束
· 后端思维之高并发处理方案
· 千万级大表的优化技巧
· 在 VS Code 中,一键安装 MCP Server!
· 10年+ .NET Coder 心语 ── 继承的思维:从思维模式到架构设计的深度解析