Java如何显示所有正在运行的线程?

在Java编程中,如何显示所有正在运行的线程?

以下示例演示如何使用getName()方法显示所有正在运行的线程的名称。

package com.yiibai;

public class DisplayRunningThread extends Thread {
    public static void main(String[] args) {
        DisplayRunningThread t1 = new DisplayRunningThread();
        t1.setName("thread1");
        t1.start();
        DisplayRunningThread t2 = new DisplayRunningThread();
        t2.setName("thread2");
        t2.start();
        ThreadGroup currentGroup = Thread.currentThread().getThreadGroup();
        int noThreads = currentGroup.activeCount();
        Thread[] lstThreads = new Thread[noThreads];
        currentGroup.enumerate(lstThreads);

        for (int i = 0; i < noThreads; i++){
            System.out.println("Thread No:" + i + " = " + lstThreads[i].getName());
        }
    }
}
Java

上述代码示例将产生以下结果 -

Thread No:0 = main
Thread No:1 = thread1
Thread No:2 = thread2
posted @ 2018-09-09 13:36  borter  阅读(739)  评论(0编辑  收藏  举报