Home » Java programming language

Java ThreadGroup class activeCount() method with example

ThreadGroup class activeCount() method: Here, we are going to learn about the activeCount() method of ThreadGroup class with its syntax and example.
Submitted by Preeti Jain, on September 13, 2019

ThreadGroup class activeCount() method

  • activeCount() method is available in java.lang package.
  • activeCount() method is a static method, it is accessible with the class name too.
  • activeCount() method is used to return the number of active threads in the current threads thread group.
  • activeCount() method does not raise any exception when no active thread is live.

Syntax:

    static int activeCount();

Parameter(s):

  • This method does not accept any parameter.

Return value:

The return type of this method is int, it returns the count of active threads in the current thread of thread's group.

Example:

// Java program to demonstrate the example of 
// activeCount() method of ThreadGroup Class.

import java.lang.*;

class ActiveCount extends Thread {
    // Override run() of Thread class
    public void run() {
        String name = Thread.currentThread().getName();
        System.out.println(name + " " + "finish executing");
    }
}

public class Main {
    public static void main(String[] args) {
        ActiveCount ac = new ActiveCount();
        try {

            // We are creating an object of ThreadGroup class
            ThreadGroup tg1 = new ThreadGroup("ThreadGroup 1");
            ThreadGroup tg2 = new ThreadGroup("ThreadGroup 2");

            // We are creating an object of Thread class and 
            // we are assigning the ThreadGroup of both the thread

            Thread th1 = new Thread(tg1, ac, "First Thread");
            Thread th2 = new Thread(tg2, ac, "Second Thread");

            // Calling start() method with Thread class object 
            // of Thread class 

            th1.start();
            th2.start();

            // Here we are counting active thread in ThreadGroup

            System.out.print("Active thread in : " + tg1.getName() + "-");
            System.out.println(tg1.activeCount());

            System.out.print("Active thread in : " + tg2.getName() + "-");
            System.out.println(tg2.activeCount());


            th1.join();
            th2.join();

        } catch (Exception ex) {

            System.out.println(ex.getMessage());
        }
    }
}

Output

E:\Programs>javac Main.java
E:\Programs>java Main
Second Thread finish executing
Active thread in : ThreadGroup 1-1
Active thread in : ThreadGroup 2-0
First Thread finish executing


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.