Tuesday 4 March 2014

show all active threads: enumerate

public static int enumerate(Thread tarray[])
enumerate method copies all the active threads from the current threads threadgroup and its subgroups into an array.

public class EnumerateEx implements Runnable {
 public void run(){
  try{
   Thread.currentThread().sleep(2000);
  }
  catch(InterruptedException e){
  }
 }

 public static void main(String args[]){
  EnumerateEx task1 = new EnumerateEx();
  EnumerateEx task2 = new EnumerateEx();
  EnumerateEx task3 = new EnumerateEx();

  Thread t1 = new Thread(task1);
  Thread t2 = new Thread(task2);
  Thread t3 = new Thread(task3);

  t1.start();
  t2.start();
  t3.start();

  int count = Thread.activeCount();
  Thread t[] = new Thread[count];
  Thread.enumerate(t);

  for(int i=0; i< t.length; i++){
   System.out.println(t[i]);
  }
 }
}
  
 Output
Thread[main,5,main]
Thread[Thread-0,5,main]
Thread[Thread-1,5,main]
Thread[Thread-2,5,main]

The implementation of enumerate looks like below

public static int enumerate(Thread tarray[]) {
     return currentThread().getThreadGroup().enumerate(tarray);
}





Active Threads Count                                                 Thread Groups                                                 Home

No comments:

Post a Comment