Java 实例 - 获取所有线程

以下实例演示了如何使用 getName() 方法获取所有正在运行的线程:

Main.java 文件

  1. public class Main extends Thread {
  2. public static void main(String[] args) {
  3. Main t1 = new Main();
  4. t1.setName("thread1");
  5. t1.start();
  6. ThreadGroup currentGroup =
  7. Thread.currentThread().getThreadGroup();
  8. int noThreads = currentGroup.activeCount();
  9. Thread[] lstThreads = new Thread[noThreads];
  10. currentGroup.enumerate(lstThreads);
  11. for (int i = 0; i < noThreads; i++)
  12. System.out.println("线程号:" + i + " = " + lstThreads[i].getName());
  13. }
  14. }

以上代码运行输出结果为:

  1. 线程号:0 = main
  2. 线程号:1 = thread1