Java: 获得所有线程

 

Getting a list of running Threads

 

public static String[] getThreadNames() {   
  ThreadGroup group = Thread.currentThread().getThreadGroup();   
  ThreadGroup parent = null;   
  while ( (parent = group.getParent()) != null ) {   
    group = parent;   
  }   
  Thread[] threads = new Thread[group.activeCount()];   
  group.enumerate(threads);   
  java.util.HashSet set = new java.util.HashSet();   
  for (int i=0; i < threads.length; ++i) {   
    if (threads[i] != null && threads[i].isAlive()) {   
      try {   
        set.add(threads[i].getThreadGroup().getName()+","  
                +threads[i].getName()+","  
                +threads[i].getPriority());   
      } catch (Throwable e) {e.printStackTrace();}   
    }   
  }   
  String[] result = (String[]) set.toArray(new String[0]);   
  java.util.Arrays.sort(result);   
  return result;   
}  
 

 

你可能感兴趣的:(java,thread)