| ||||
Copyright 1999 Sams Publishing |
|
Finding All the Threads in a Thread Group |
The activeCount() method returns the number of active threads in a particular ThreadGroup and all of its subgroups . Keep in mind that this can be dynamically changing, as new threads might be created and existing threads might be dying. |
To get a reference to all of the threads in a ThreadGroup and all of its subgroups, the enumerate(Thread[]) method can be used. If you dont want to include a recursive search of the subgroups, use enumerate(Thread[], false) instead. Both methods return the number of threads copied into the passed array. If the array is not big enough, the extra threads are silently ignored. To get an idea of how big the destination array needs to be, you can use the value returned from activeCount() . This code tries to capture all of the threads in group and its subgroups: |
ThreadGroup group = // ... |
int estimatedSize = 2 * group. activeCount (); |
Thread[] dest = new Thread[estimatedSize]; |
int actualSize = group. enumerate (dest); |
The count returned from activeCount() is doubled in an attempt to be sure that the destination array is large enough. Based on estimatedSize , a destination array for the threads is allocated and referred to by dest . The enumerate(Thread[]) method copies up to dest.length threads into dest . The number of threads copied is returned and stored in actualSize . If actualSize is equal to dest.length , there is a good chance that dest was not big enough. Generally, actualSize is less than dest.length and indicates the number of valid threads n dest . |
| |||
Toc |