What is Thread.activeCount() in Java?

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.

Syntax

The syntax of the activeCount() method is as follows.


static int activeCount()

Parameters

It does not take any parameters.

Return value

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.

Code

The code below illustrates how Java threads work and how we can use the activeCount() method.

// demo code, get count for current running threads
import 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 group
ThreadGroup group = new ThreadGroup("Parent Group Thread");
// creating 1st thread
EdPresso thread1 = new EdPresso("Thread-1", group);
// creating 2nd thread
EdPresso thread2 = new EdPresso("Thread-2", group);
// creating 3rd thread
EdPresso thread3 = new EdPresso("Thread-3", group);
// checking the number of active thread
System.out.println("number of active threads: "+ group.activeCount());
}
}

Explanation

  • 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 parent Thread classsuper(threadgroup, threadname) whenever an instance of the 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.

Free Resources