在 Java 中,ExecutorService 本身没有直接提供“监控接口”,但可以通过它提供的方法、结合线程池实现类(如 ThreadPoolExecutor)以及额外工具来进行监控。下面从常用方式 → 关键指标 → 实战示例 → 高级方案逐步说明。
ExecutorService 提供的方法有限,但足够判断“是否还在跑”:
ExecutorService executor = Executors.newFixedThreadPool(10);
executor.isShutdown(); // 是否已调用 shutdown
executor.isTerminated(); // 是否所有任务都已结束
⚠️ 只能判断状态,看不到队列、线程数、活跃任务数。
如果你用的是:
ExecutorService executor = Executors.newFixedThreadPool(n);
实际上返回的是 ThreadPoolExecutor,可以直接强转:
ThreadPoolExecutor pool = (ThreadPoolExecutor) executor;
| 方法 | 含义 |
|---|---|
getPoolSize() |
当前线程数 |
getActiveCount() |
正在执行任务的线程数 |
getCorePoolSize() |
核心线程数 |
getMaximumPoolSize() |
最大线程数 |
getQueue().size() |
等待执行的任务数 |
getCompletedTaskCount() |
已完成任务总数 |
getTaskCount() |
总任务数(已完成 + 正在执行 + 排队) |
System.out.println("活跃线程数: " + pool.getActiveCount());
System.out.println("队列长度: " + pool.getQueue().size());
System.out.println("已完成任务: " + pool.getCompletedTaskCount());
ScheduledExecutorService monitor = Executors.newSingleThreadScheduledExecutor();
monitor.scheduleAtFixedRate(() -> {
ThreadPoolExecutor pool = (ThreadPoolExecutor) executor;
System.out.printf(
"active=%d, pool=%d, queue=%d, completed=%d%n",
pool.getActiveCount(),
pool.getPoolSize(),
pool.getQueue().size(),
pool.getCompletedTaskCount()
);
}, 0, 5, TimeUnit.SECONDS);
afterExecute(推荐)ThreadPoolExecutor pool = new ThreadPoolExecutor(
10, 10, 0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<>()
) {
@Override
protected void afterExecute(Runnable r, Throwable t) {
System.out.println("任务执行完成,异常:" + t);
}
};
✅ 可统计:
ExecutorService executor = Executors.newFixedThreadPool(10);
ExecutorService monitored = ExecutorServiceMetrics.monitor(
Metrics.globalRegistry,
executor,
"my-executor"
);
暴露指标:
executor.activeexecutor.completedexecutor.queued然后通过 Prometheus + Grafana 可视化。
ThreadPoolExecutor 本身不支持 JMX,但你可以:
management:
endpoints:
web:
exposure:
include: metrics
访问:
/actuator/metrics/executor.active
✅ 队列是否堆积
✅ 活跃线程是否长期 = 最大线程
✅ 任务失败率
✅ 平均执行时间
| 现象 | 可能原因 |
|---|---|
| queue 一直在涨 | 消费太慢 / 线程数不够 |
| active = max 且 queue 满 | 资源瓶颈 |
| completed 不增长 | 任务卡死 / 死锁 |
如果你愿意,可以告诉我:
我可以给你一套可直接用的监控模板。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。