背景:有个需求需要打印tomcat当前的线程数量
实现:
@Controller
public class TestThreadController {
@RequestMapping("/threadInfo")
@ResponseBody
public String threadInfo() {
int activeCount = 0;
int blockedCount = 0;
int idleCount = 0;
int timedWaitingCount = 0;
int terminatedCount = 0;
int count = 0;
ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
for (ThreadInfo threadInfo : threadMXBean.getThreadInfo(threadMXBean.getAllThreadIds(), 0)) {
if (threadInfo.getThreadState() == Thread.State.RUNNABLE) {
activeCount++;
count++;
} else if (threadInfo.getThreadState() == Thread.State.WAITING) {
idleCount++;
count++;
} else if (threadInfo.getThreadState() == Thread.State.BLOCKED) {
blockedCount++;
count++;
} else if (threadInfo.getThreadState() == Thread.State.TERMINATED) {
terminatedCount++;
count++;
} else if (threadInfo.getThreadState() == Thread.State.TIMED_WAITING) {
timedWaitingCount++;
count++;
}
}
return String.format("activeCount:%d,blockedCount:%d,idleCount:%d,timedWaitingCount:%d,terminatedCount:%d,count:%d",
activeCount, blockedCount, idleCount, timedWaitingCount, terminatedCount, count);
}
}
实践验证:
程序启动,我的端口是8080:
使用java监测工具验证:
和实时线程是一致的。
提示:这个方法里的核心类属于java.lang包,所以该方法理论上可以监测任何使用java运行的项目的线程数。监测tomcat线程数必然可以。