Get a list of all threads currently running in Java

后端 未结 13 1636
[愿得一人]
[愿得一人] 2020-11-22 02:30

Is there any way I can get a list of all running threads in the current JVM (including the threads not started by my class)?

Is it also possible to get the

13条回答
  •  执念已碎
    2020-11-22 03:10

    Get a handle to the root ThreadGroup, like this:

    ThreadGroup rootGroup = Thread.currentThread().getThreadGroup();
    ThreadGroup parentGroup;
    while ((parentGroup = rootGroup.getParent()) != null) {
        rootGroup = parentGroup;
    }
    

    Now, call the enumerate() function on the root group repeatedly. The second argument lets you get all threads, recursively:

    Thread[] threads = new Thread[rootGroup.activeCount()];
    while (rootGroup.enumerate(threads, true ) == threads.length) {
        threads = new Thread[threads.length * 2];
    }
    

    Note how we call enumerate() repeatedly until the array is large enough to contain all entries.

提交回复
热议问题