How do I get number of active thread group?

Use method activeGroupCount() of ThreadGroup class to get estimate number of active groups in the thread group and use activeCount() to get estimate number of active threads in a thread group.

package org.kodejava.example.lang;

public class ActiveGroupCount {
    public static void main(String[] args) {
        ThreadGroup root = new ThreadGroup("RootGroup");
        ThreadGroup server = new ThreadGroup(root, "ServerGroup");
        ThreadGroup client = new ThreadGroup(root, "ClientGroup");

        Thread t1 = new Thread(server, new ServerThread(), "ServerThread");
        Thread t2 = new Thread(client, new ClientThread(), "ClientThread");

        t1.start();
        t2.start();

        //
        // Get estimate active groups in 'root' thread group
        //
        int activeGroup = root.activeGroupCount();
        System.out.format("Estimated active group in %s is %d%n",
                root.getName(), activeGroup);

        //
        // Get estimate active threads in 'root' thread group
        //
        int activeThread = root.activeCount();
        System.out.format("Estimated active thread in %s is %d%n",
                root.getName(), activeThread);
    }
}

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


class ClientThread implements Runnable {
    public void run() {
        System.out.println("Running - Client Thread..");
    }
}

The example above print the following example output:

Running - Server Thread..
Running - Client Thread..
Estimated active group in RootGroup is 2
Estimated active thread in RootGroup is 0
Wayan Saryada

Wayan Saryada

A programmer, runner, recreational diver, currently living in the island of Bali, Indonesia. Mostly programming in Java, creating web based application with Spring Framework, JPA, etc. If you need help on Java programming you can hire me on Fiverr.
Wayan Saryada

Leave a Reply