I got this sample from JavaPassion site.It's great one for beginners
it's very good sample about getting current Threads information
-----------------------------------------------------------------------------------
public class DisplayAllThreads { public static void main(String[] args) { // Start three threads first. They should belong // to a same ThreadsGroup. new SimpleThread("Boston").start(); new SimpleThread("New York").start(); new SimpleThread("Seoul").start(); Thread[] tarray = findAllThreads(); for (int i=0; i<tarray.length;i++){ System.out.println("Thread " + tarray[i].getName() + " in thread group " + tarray[i].getThreadGroup().getName()); } } // Create an array of all threads in the system. public static Thread[] findAllThreads() { ThreadGroup group = Thread.currentThread().getThreadGroup(); ThreadGroup topGroup = group; while (group != null) { topGroup = group; group = group.getParent(); } int estimatedSize = topGroup.activeCount() * 2; Thread[] slackList = new Thread[estimatedSize]; int actualSize = topGroup.enumerate(slackList); Thread[] list = new Thread[actualSize]; System.arraycopy(slackList, 0, list, 0, actualSize); return list; } } class SimpleThread extends Thread { public SimpleThread(String str) { super(str); } public void run() { for (int i = 0; i < 5; i++) { // System.out.format("%d %s%n", i, getName()); try { sleep((long)(Math.random() * 1000)); } catch (InterruptedException e) {} } System.out.format("DONE! %s%n", getName()); } }
All i need to know Why when getting total number of active thread He multiply 2
this line...
int estimatedSize = topGroup.activeCount() * 2;