How do I count active thread in a thread group?

This example describe how to get the number of active threads in this thread group. The result might not reflect concurrent activity, and might be affected by the presence of certain system threads.

Due to the inherently imprecise nature of the result, it is recommended that this method only be used for informational purposes.

package org.kodejava.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();

        // Get an estimate number of active thread of the thread
        // group.
        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..");
    }
}
Wayan

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.