0

I was looking for a solution to get the amount of threads running in my program. I ended up with this two solutions from Get a List of all Threads currently running in Java.

Using

Set<Thread> threadSet = Thread.getAllStackTraces().keySet();
runningThreads = threadSet.size();

I end up with 75 threads.


Using

ThreadGroup rootGroup = Thread.currentThread( ).getThreadGroup( );
ThreadGroup parentGroup;
while ( ( parentGroup = rootGroup.getParent() ) != null ) {
        rootGroup = parentGroup;
}
Thread[] threads = new Thread[ rootGroup.activeCount() ];
while ( rootGroup.enumerate( threads, true ) == threads.length ) {
        threads = new Thread[ threads.length * 2 ];
}
runningThreads = threads.length;

I end up with the exact doubled amount of threads -> 150


I was wondering why the theads are doubled and saw this threads = new Thread[ threads.length * 2 ];.

Why do we multiply with 2 in this method?

EDIT:
Maybe I have malformed my question. Even if it is answered right now I want to correct it. The question is why we multiply with 2 even the size is already big enough and therefor get the wrong amount of currently running threads.

4

1 回答 1

2

根据ThreadGroup 的文档,该方法

public int enumerate(Thread[] list,
            boolean recurse)

将递归枚举子组。但是,它只返回可以填充list参数的线程数。length因此,如果代码观察到您已经收到确切的元素,list并且假设有更多线程要枚举但数组大小不够,则代码会尝试分配更多大小来列出。

因此,当循环终止时,即使您在 中 有length元素list,最后几个元素也将为空,您将不得不在确定线程数时忽略它们

于 2013-07-09T13:54:15.627 回答