Thread’s activeCount() is a static method which returns a number of active threads. Internally it calls ThreadGroup’s activeCount() method.
Declaration – public static int activeCount()
Let’s see an example –
package multithreading; public class ThreadActiveCount { public static void main(String[] args) { System.out.println(Thread.activeCount()); } }
Output is – 1
In the above program by default, we have the main thread running that’s why the count is one.
Internal implementation.
public static int activeCount() { return currentThread().getThreadGroup().activeCount(); }
Example 2 – In this example, we will create two thread and we will see what is count.
package multithreading; public class ThreadActiveCount { public static void main(String[] args) { Thread thread1 = new Thread() { public void run() { System.out.println("Using Thread class thread created"); } }; thread1.start(); Runnable r = new Runnable() { public void run() { System.out.println("Using Runnable interface thread created"); } }; Thread thread2 = new Thread(r); thread2.start(); System.out.println(Thread.activeCount()); } }
Output is –
3
Using Thread class thread created
Using Runnable interface thread created
Note – In the above example, we have created Active thread count may vary because before executing line 22 it may possible user-defined thread has been stopped.