Get a list of all threads currently running in Java

后端 未结 13 1637
[愿得一人]
[愿得一人] 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:13

        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

提交回复
热议问题