Java如何计算线程组中的活动线程?

本示例说明如何获取此线程组中活动线程的数量。结果可能无法反映并发活动,并且可能会受到某些系统线程的影响。

由于结果本身的不精确性,建议仅将此方法用于信息查看。

package org.nhooo.example.lang;

public class ThreadGroupActiveThread {
    public static void main(String[] args) {
        ThreadGroup threadGroup = new ThreadGroup("TestThread");

        Thread t1 = new Thread(threadGroup, new Server(), "Server1");
        Thread t2 = new Thread(threadGroup, new Server(), "Server2");
        Thread t3 = new Thread(threadGroup, new Server(), "Server3");
        Thread t4 = new Thread(threadGroup, new Server(), "Server4");

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

        // 获取线程的活动线程的估计数量
        // 组。
        int activeThread = threadGroup.activeCount();
        System.out.format("Number of active threads of %s is %d %n",
                threadGroup.getName(), activeThread);
    }
}

class Server implements Runnable {
    public void run() {
        System.out.println("Running..");
    }
}