Java: 获得所有线程

我想在一个时刻查看java中还存在的所有线程, 于是google到了这里.

http://billharlan.com/pub/papers/javatips.html.

 

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,html,Google)