VOOZH about

URL: https://www.geeksforgeeks.org/java/java-thread-activecount-method/

⇱ Java Thread.activeCount() Method - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Java Thread.activeCount() Method

Last Updated : 23 Jul, 2025

Thread.activeCount() method is a static method of the Thread class in Java that returns the number of active threads in the current thread's thread group and its subgroups. It provides an estimate of how many threads are currently active and being executed in the program, including threads from any subgroups.

Example 1: Below is an example that demonstrates the usage of the Thread.activeCount() method.


Output
Number of active threads: 3

Explanation:

  • In the above example, we created some example threads and checked the currently active threads using the activeCount() method.
  • Every Java program starts with a main thread. This thread is responsible for executing the code within the main method that's why the count is 3.
  • The activeCount() method gives the estimation of active threads.
  • It is used to monitor the different states of threads in a Multithreaded environment.

Syntax of Thread.activeCount() Method

public static int activeCount();

  • Return Type: It returns the number of threads that are currently active in the thread group of the current thread.
  • Behavior:
    • Thread Group: The method counts all active threads in the current thread's thread group and any subgroups of that group.
    • Dynamic Nature: The count is an estimate since thread states can change dynamically (e.g., threads starting or finishing).

Example 2: In this example, we will use the Thread.activeCount() to check the number of active threads in a thread pool environment.


Output
Initial: 1
Final: 3
Task 2 is starting.
Task 1 is starting.
Task 2 has finished.
Task 1 has finished.

Explanation:

  • The above program first creates a thread pool with two threads and prints the initial thread count.
  • Then, two tasks are submitted to the executor, and the executor is immediately shut down.
  • Then it prints the final thread count, effectively showing the change in active threads before and after task execution.
  • The returns an estimate of the number of active threads in the current thread's thread group.
  • The main thread is itself a thread and part of the thread group, it is included in the count.
Comment