«Back to Home

Core Java

Topics

ThreadGroup Class In Java

ThreadGroup Class

A group of multiple threads in a single object is called a ThreadGroup in Java.
 
With the help of ThreadGroup class, we can suspend, resume or interrupt group of threads with a single method call.
 
Suspend () method, resume () method and stop () method are deprecated now.
 
ThreadGroup is implemented by java.lang.ThreadGroup class.
 
Constructors of ThreadGroup class

ThreadGroup(String name)

It is used to create a thread group with the given name.
 
ThreadGroup(ThreadGroup parent, String name)

It is used to create a thread group with the given parent group and name.
 
Methods of ThreadGroup class

int activeCount()

This method is used to return no. of threads running in current group.
 
int activeGroupCount()

This method is used to return a no. of active group in this thread group.
 
void destroy()

This method is used to destroy this thread group and all its sub groups.
 
String getName()

This method is used to return the name of this group.
 
ThreadGroup getParent()

This method is used to return the parent of this group.
 
void interrupt()

This method is used to interrupt all the threads of the group.
 
void list()

This method is used to print the information of the group to standard console.
 
Let’s see an example of ThreadGroup, given below.
 
Code
  1. public class ThreadGroupExample implements Runnable {  
  2.     public void run() {  
  3.         System.out.println(Thread.currentThread().getName());  
  4.     }  
  5.     public static void main(String[] args) {  
  6.         ThreadGroupExample obj = new ThreadGroupExample();  
  7.         ThreadGroup tg = new ThreadGroup("Main ThreadGroup");  
  8.         Thread t1 = new Thread(tg, obj, "thread1");  
  9.         t1.start();  
  10.         Thread t2 = new Thread(tg, obj, "thread2");  
  11.         t2.start();  
  12.         Thread t3 = new Thread(tg, obj, "thread3");  
  13.         t3.start();  
  14.         System.out.println("Name of ThreadGroup : " + tg.getName());  
  15.         tg.list();  
  16.     }  
  17. }  
32

Output

33

In the example, mentioned above, we created three threads, which belong to one group. Here, tg is the thread group name, the ThreadGroupExample class implements Runnable interface and "thread1", "thread2", "thread3" are the thread names and at the present, we can interrupt all the threads easily.

Let’s see an example, given below.

34
 
Summary

Thus, we learnt a group of multiple threads in a single object is called as a ThreadGroup and also learnt how to create it in Java.