是否有任何方法可以获得当前JVM中所有正在运行的线程的列表(包括不是由我的类启动的线程)?
是否也可以获得列表中所有线程的Thread和Class对象?
我希望能够通过代码来实现。
是否有任何方法可以获得当前JVM中所有正在运行的线程的列表(包括不是由我的类启动的线程)?
是否也可以获得列表中所有线程的Thread和Class对象?
我希望能够通过代码来实现。
当前回答
您可以使用返回所有活动线程id的getAllThreadIds。当此方法返回时,返回数组中包含的某些线程可能已经终止。
ManagementFactory.getThreadMXBean().getAllThreadIds()
其他回答
public static void main(String[] args) {
// Walk up all the way to the root thread group
ThreadGroup rootGroup = Thread.currentThread().getThreadGroup();
ThreadGroup parent;
while ((parent = rootGroup.getParent()) != null) {
rootGroup = parent;
}
listThreads(rootGroup, "");
}
// List all threads and recursively list all subgroup
public static void listThreads(ThreadGroup group, String indent) {
System.out.println(indent + "Group[" + group.getName() +
":" + group.getClass()+"]");
int nt = group.activeCount();
Thread[] threads = new Thread[nt*2 + 10]; //nt is not accurate
nt = group.enumerate(threads, false);
// List every thread in the group
for (int i=0; i<nt; i++) {
Thread t = threads[i];
System.out.println(indent + " Thread[" + t.getName()
+ ":" + t.getClass() + "]");
}
// Recursively list all subgroups
int ng = group.activeGroupCount();
ThreadGroup[] groups = new ThreadGroup[ng*2 + 10];
ng = group.enumerate(groups, false);
for (int i=0; i<ng; i++) {
listThreads(groups[i], indent + " ");
}
}
在Groovy中,你可以调用私有方法
// Get a snapshot of the list of all threads
Thread[] threads = Thread.getThreads()
在Java中,只要安全管理器允许,就可以使用反射调用该方法。
获取一个可迭代集:
Set<Thread> threadSet = Thread.getAllStackTraces().keySet();
性能:0毫秒,12个线程(Azul JVM 16.0.1, Windows 10, Ryzen 5600X)。
Apache Commons用户可以使用ThreadUtils。当前实现使用前面概述的线程组方法。
for (Thread t : ThreadUtils.getAllThreads()) {
System.out.println(t.getName() + ", " + t.isDaemon());
}
您可以使用返回所有活动线程id的getAllThreadIds。当此方法返回时,返回数组中包含的某些线程可能已经终止。
ManagementFactory.getThreadMXBean().getAllThreadIds()