ADVERTISEMENT
ADVERTISEMENT

Java program to count active threads of a thread group

Java example to count active threads of a thread group.
Submitted by Nidhi, on April 10, 2022

Problem Solution:

In this program, we will create a thread group using ThreadGroup class and add child threads to the group and count active threads using activeCount() method.

Program/Source Code:

The source code to count active threads of a thread group is given below. The given program is compiled and executed successfully.

// Java program to count active threads 
// of a thread group

class MyThread extends Thread {
  MyThread(String threadname, ThreadGroup tg) {
    super(tg, threadname);
    start();
  }
  public void run() {
    System.out.println(Thread.currentThread().getName() + " is running");
  }
}

public class Main {
  public static void main(String[] args) {
    try {
      ThreadGroup group = new ThreadGroup("Parent thread");

      MyThread t1 = new MyThread("Child Thread1", group);
      MyThread t2 = new MyThread("Child Thread2", group);
      MyThread t3 = new MyThread("Child Thread3", group);

      System.out.println("Total active threads: " + group.activeCount());
    } catch (Exception e) {
      System.out.println(e);
    }
  }
}

Output:

Total active threads: 3
Child Thread2 is running
Child Thread1 is running
Child Thread3 is running

Explanation:

In the above program, we created two classes MyThread and Main. We created MyThread class by extending the Thread class.

The Main class contains a main() method. The main() method is the entry point for the program. Here, we created an object of ThreadGroup class and added the child thread into the thread group. After that, we count the activated threads and printed the result.

Java Threading Programs »


ADVERTISEMENT
ADVERTISEMENT


Comments and Discussions!



ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.