The implementation of the Java.lang.Thread
package contains the activeCount()
static method which counts and returns the number of active threads in the current thread group and subgroups.
The syntax of the activeCount()
method is as follows.
static int activeCount()
It does not take any parameters.
The activeCount()
method returns the current thread count as an integer value.
The value returned by this method will be an estimation because the number of threads changes dynamically.
The code below illustrates how Java threads work and how we can use the activeCount()
method.
// demo code, get count for current running threadsimport java.lang.Thread;public class EdPresso extends Thread{EdPresso(String threadname, ThreadGroup threadgroup){super(threadgroup, threadname);start();}public void run(){System.out.println("Current running thread name: "+Thread.currentThread().getName());}public static void main(String arg[]){// creating the thread groupThreadGroup group = new ThreadGroup("Parent Group Thread");// creating 1st threadEdPresso thread1 = new EdPresso("Thread-1", group);// creating 2nd threadEdPresso thread2 = new EdPresso("Thread-2", group);// creating 3rd threadEdPresso thread3 = new EdPresso("Thread-3", group);// checking the number of active threadSystem.out.println("number of active threads: "+ group.activeCount());}}
The EdPresso
class extends the built-in Thread
class to implement threads in the code above.
In line 17, we instantiate the ThreadGroup
, which helps group multiple threads in Java.
The constructor of the Edpresso
class initializes threads by calling the constructor of the Thread
classsuper(threadgroup, threadname)
Edpresso
class is declared, e.g., in lines 19, 21, and 23.
In line 25, the activeCount()
method returns the current count of running threads, which is printed accordingly.