ThreadGroup in Java


JavaViews 2894

ThreadGroup in Java

A ThreadGroup in Java represents a group of threads or thread groups and belongs to the java.lang.ThreadGroup class. The main advantage of a thread group is that we can perform operations like suspend, resume, or interrupt for all threads using a single function call. Every thread in a thread group has a parent thread except the initial thread and hence it represents a tree structure. It can access all the information about its own thread group. ThreadGroup class is very useful when we want to perform the same operation on multiple threads.

ThreadGroup in Java

Constructors of ThreadGroup

Below are the constructors in Java ThreadGroup.

ConstructorDescription
ThreadGroup(String name)Creates a thread group with the specified name
ThreadGroup(ThreadGroup parent, String name)Creates a thread group with the specified thread group parent and name

Methods of ThreadGroup

The ThreadGroup class in Java has the below methods to perform various operations.

MethodDescription
int activeCount()Returns the number of active threads in the Thread group
int activeGroupCount()Returns the number of active threads groups in the specified group
void checkAccess()Checks if the current thread has permission to modify the groups access
void destroy()Destroys the thread group
int enumerate(Thread[] list)Copies every thread in the thread group to the specified array
int enumerate(ThreadGroup[] list)Copies every active subgroup in the thread group to the specified array
int enumerate(Thread[] list, boolean recurse)Copies every thread in the thread group to the specified array. If recurse is true, it recursively calls this operation
int enumerate(ThreadGroup[] list, boolean recurse)Copies every active subgroup in the thread group to the specified array. If recurse is true, it recursively calls this operation
int getMaximumPriority()Returns the maximum priority of the thread group
String getName()Returns the name of the thread group
ThreadGroup getParent()Returns the parent of the thread group
void interrupt()Interrupts all the threads in the thread group
boolean isDaemon()Checks if the thread group is daemon
boolean isDestroyed()Checks if the thread group is destroyed
void list()Prints information about the thread group to the standard output stream
boolean parentOf(ThreadGroup tg)Checks if the thread group is the specified thread group argument or its ancestor thread groups
void setDaemon(boolean daemon)Sets the daemon status of the thread group
void setMaxPriority(int p)Sets the specified maximum priority for the thread group

Example of  Java ThreadGroup methods:

This example shows how to use various methods of the ThreadGroup class in Java. We have created two ThreadGroups named “Group1” and “Group2” where Group1 is the parent of Group2. To retrieve the number of active threads, we use activeCount() method, and to get the number of active thread groups, we can use the activeGroupCount() method. The getMaxPriority() returns the maximum priority of the available threads. The getName() retrieves the thread group name. We can also check if a thread group is a parent of another group using the parentOf() method and get the parent name using the getParent() method. The checkAccess() method checks if the thread groups have the necessary permissions to retrieve the group information. Finally, we can list all the threads in the thread group using the list() method.

public class ThreadGroupDemo extends Thread {

  public ThreadGroupDemo(String name, ThreadGroup tg) {
    super(tg,name);
  }
  
  public void run() {
    System.out.println("Running " + Thread.currentThread().getName());
  }

  public static void main(String[] args) {
    ThreadGroup tg = new ThreadGroup("Group1");
    ThreadGroup tg1 = new ThreadGroup(tg, "Group2");
  
    
    ThreadGroupDemo t1 = new ThreadGroupDemo("Thread1", tg);
    ThreadGroupDemo t2 = new ThreadGroupDemo("Thread2", tg);
    
    ThreadGroupDemo t3 = new ThreadGroupDemo("Thread3", tg1);
    
    t1.start();
    t2.start();
    t3.start();
    
    System.out.println("Number of active threads: " + tg.activeCount());
    System.out.println("Number of active thread groups: " + tg.activeGroupCount());
    System.out.println("Maximum priority: " + tg.getMaxPriority());
    System.out.println("Thread group name: " + tg.getName());
    System.out.println("Child thread group name: "+ tg1.getName());
    System.out.println(tg.parentOf(tg1));
    System.out.println("Parent thread group: " + tg1.getParent());
    
    tg.checkAccess();
    System.out.println(tg.getName() + " has access");
    
    tg1.checkAccess();
    System.out.println(tg1.getName() + " has access");

    System.out.println("List the information of thread group using the list method: ");
    tg.list();
  }

}
Running Thread3
Running Thread2
Number of active threads: 3
Running Thread1
Number of active thread groups: 1
Maximum priority: 10
Thread group name: Group1
Child thread group name: Group2
true
Parent thread group: java.lang.ThreadGroup[name=Group1,maxpri=10]
Group1 has access
Group2 has access
List the information of thread group using the list method: 
java.lang.ThreadGroup[name=Group1,maxpri=10]
    java.lang.ThreadGroup[name=Group2,maxpri=10]

Example: destroy() method – Java ThreadGroup

This example demonstrates how to destroy a thread group in Java using the destroy() method and check if it is destroyed using the isDestroyed() method. Before destroying the thread group, we need to wait until the threads have completed the execution, else it will throw an InterruptedException. For this, we use the join() method of the Thread class.

public class ThreadGroupEx extends Thread{

  public ThreadGroupEx(ThreadGroup tg, String name) {
    super(tg,name);
  }
  
  public void run() {
    System.out.println(Thread.currentThread().getName() + " is running");
  }

  public static void main(String[] args) throws InterruptedException {
    ThreadGroup tg = new ThreadGroup("Group1");
    
    ThreadGroupEx t1 = new ThreadGroupEx(tg, "Thread1");
    ThreadGroupEx t2 = new ThreadGroupEx(tg, "Thread2");
    t1.start();
    t2.start();
    
    t1.join();
    t2.join();
    
    tg.destroy();
    System.out.println(tg.getName() + " destroyed");
    System.out.println("Is thread group destroyed: " + tg.isDestroyed());

  }

}
Thread2 is running
Thread1 is running
Group1 destroyed
Is thread group destroyed: true

Example: interrupt() method – Java ThreadGroup

This is an example of interrupting a thread group using the interrupt() method.

public class InterruptThread extends Thread{

  public InterruptThread(ThreadGroup tg, String name) {
    super(tg,name);
  }
  
  public void run() {
    System.out.println(Thread.currentThread().getName() + " is running");
  }

  public static void main(String[] args) {
    ThreadGroup tg = new ThreadGroup("Group1");
    
    InterruptThread t1 = new InterruptThread(tg,"Thread1");
    t1.start();
    
    t1.interrupt();
    System.out.println(tg.getName() + " interrupted");
  
  }

}
Group1 interrupted
Thread1 is running

Example: enumerate() method – Java ThreadGroup

In this example, we can see how to copy the threads into an array using the enumerate() method. Here, we create 2 threads and copy them into an array, and print the thread names using the for loop.

public class EnumerateThreadDemo extends Thread {

  public EnumerateThreadDemo(ThreadGroup tg, String name) {
    super(tg, name);
  }
  
  public void run() {
    System.out.println(Thread.currentThread().getName() + " is running");
  }

  public static void main(String[] args) {
    ThreadGroup tg = new ThreadGroup("Group1");
    

    EnumerateThreadDemo t1 = new EnumerateThreadDemo(tg, "Thread1");
    EnumerateThreadDemo t2 = new EnumerateThreadDemo(tg, "Thread2");
    
    t1.start();
    t2.start();
    
    Thread[] tarr = new Thread[tg.activeCount()];
    int cnt = tg.enumerate(tarr);
    
    for(int i=0;i<cnt;i++)
      System.out.println(tarr[i].getName());
  }

}
Thread1
Thread2
Thread1 is running
Thread2 is running

Below is another example of enumerate() method, when we set the recurse parameter true. In this case, it recurses through the child thread groups as well. That’s the reason it also prints thread3.

public class EnumerateThreadDemo extends Thread {

  public EnumerateThreadDemo(ThreadGroup tg, String name) {
    super(tg, name);
  }
  
  public void run() {
    System.out.println(Thread.currentThread().getName() + " is running");
  }

  public static void main(String[] args) {
    ThreadGroup tg = new ThreadGroup("Group1");
    ThreadGroup tg1 = new ThreadGroup(tg,"Group2");

    EnumerateThreadDemo t1 = new EnumerateThreadDemo(tg, "Thread1");
    EnumerateThreadDemo t2 = new EnumerateThreadDemo(tg, "Thread2");
    EnumerateThreadDemo t3 = new EnumerateThreadDemo(tg1, "Thread3");
    
    t1.start();
    t2.start();
    t3.start();
    
    Thread[] tarr = new Thread[tg.activeCount()];
    int cnt = tg.enumerate(tarr, true);
    
    for(int i=0;i<cnt;i++)
      System.out.println(tarr[i].getName());
  }

}
Thread1
Thread2
Thread3
Thread1 is running
Thread2 is running
Thread3 is running

We can also use the enumerate() method to copy thread groups to an array as we can see in the below example. In this case, it prints the child thread groups to an array.

public class EnumerateThreadDemo extends Thread {

  public EnumerateThreadDemo(ThreadGroup tg, String name) {
    super(tg, name);
  }
  
  public void run() {
    System.out.println(Thread.currentThread().getName() + " is running");
  }

  public static void main(String[] args) {
    ThreadGroup tg = new ThreadGroup("Group1");
    ThreadGroup tg1 = new ThreadGroup(tg,"Group2");

    EnumerateThreadDemo t1 = new EnumerateThreadDemo(tg, "Thread1");
    EnumerateThreadDemo t2 = new EnumerateThreadDemo(tg, "Thread2");
    EnumerateThreadDemo t3 = new EnumerateThreadDemo(tg1, "Thread3");
    
    t1.start();
    t2.start();
    t3.start();
    
    ThreadGroup[] tgarr = new ThreadGroup[tg.activeCount()];
    int cnt = tg.enumerate(tgarr,true);
    for(int i=0;i<cnt;i++)
      System.out.println(tgarr[i].getName());
  }

}
Group2
Thread3 is running
Thread1 is running
Thread2 is running

 

Reference

Translate »