Grouping Threads

In Java, thread grouping refers to organizing threads into logical groups for management and control. Java provides the ThreadGroup class, which represents a group of threads. ThreadGroup offers several features for managing and manipulating threads collectively.

Creating a ThreadGroup:

To create a new ThreadGroup, you can instantiate the ThreadGroup class using its constructor. You can optionally specify the parent ThreadGroup to which the new group belongs. If no parent group is specified, the new group becomes a top-level group.

ThreadGroup tg = new ThreadGroup("myGroup");Code language: JavaScript (javascript)

Adding Threads to a ThreadGroup:

Once you have a ThreadGroup, you can add threads to it by providing the ThreadGroup instance as an argument to the Thread constructor. The newly created thread will automatically become a member of the specified ThreadGroup.

Thread thread1 = new Thread(tg, "Thread1");
Thread thread2 = new Thread(tg, "Thread2");
Code language: JavaScript (javascript)

Controlling ThreadGroup’s Behavior:

ThreadGroup provides various methods to manage its behavior. Some commonly used methods include:

i) activeCount():

   public int activeCount()
   Returns the estimated number of active threads in the ThreadGroup.Code language: PHP (php)

  ii) enumerate():

public int enumerate(Thread[] list)

Copies the active threads of the ThreadGroup into the provided Thread array.

public  int enumerate(Thread[] list, boolean recurse)

Copies the active threads of the ThreadGroup into the provided Thread array, 
including the threads in any nested ThreadGroups if recurse is set to true.Code language: PHP (php)

iii) interrupt():

public void interrupt()

Interrupts all threads in the ThreadGroup.Code language: JavaScript (javascript)

  iv) setMaxPriority():

public  void setMaxPriority(int priority)

Sets the maximum priority that threads in the ThreadGroup can have.
The priority parameter is an integer value representing the thread priority. Valid values range from Thread.MIN_PRIORITY (1) to Thread.MAX_PRIORITY (10).
Code language: JavaScript (javascript)

  v) setUncaughtExceptionHandler():

public void setUncaughtExceptionHandler(Thread.UncaughtExceptionHandler handler)

Sets the uncaught exception handler for the ThreadGroup.
The handler parameter is an instance of the Thread.UncaughtExceptionHandler interface, which defines the uncaughtException() method to handle uncaught exceptions.
Code language: CSS (css)

Vi)  getParent():

public  ThreadGroup getParent()

Returns the parent of the ThreadGroup.Code language: PHP (php)

  vii) getName():

public String getName()

Returns the name of the ThreadGroup.Code language: JavaScript (javascript)

 viii) list():

<strong> public void list()</strong>

 Prints information about the ThreadGroup to the console.Code language: HTML, XML (xml)

Sample Implementation

int activeThreads = myGroup.activeCount();
Thread[] threads = new Thread[activeThreads];
myGroup.enumerate(threads);
myGroup.interrupt();
myGroup.setMaxPriority(Thread.MAX_PRIORITY);Code language: JavaScript (javascript)

Handling Uncaught Exceptions:

When a thread in a ThreadGroup throws an uncaught exception and terminates, you can set an uncaught exception handler for the ThreadGroup. The uncaught exception handler will be invoked to handle the exception.

myGroup.setUncaughtExceptionHandler(handler);Code language: CSS (css)

Nested ThreadGroups:

ThreadGroups can be organized hierarchically, allowing for nested grouping of threads. This can be useful for organizing threads into subgroups based on different criteria.

ThreadGroup parentGroup = new ThreadGroup("ParentGroup");
ThreadGroup childGroup = new ThreadGroup(parentGroup,
"ChildGroup");Code language: JavaScript (javascript)

Program Implementation

To create a simple example program for thread grouping related to the Indian Cricket team, let’s assume we want to simulate the batting performance of three key players in the team: Virat Kohli, Rohit Sharma, and Shikhar Dhawan. We’ll use threads to represent each player’s performance, and we’ll group these threads into a ThreadGroup called “IndianCricketTeam.”

In this example, each player’s thread will generate a random score, simulating their performance in a match. We’ll create a separate thread for each player, and all three threads will be part of the “IndianCricketTeam” ThreadGroup. After the match simulation is complete, we’ll display the scores of each player.

//ThreadGroupDemo.java
import java.util.Random;
class IndianPlayerThread extends Thread {
    private String playerName;
    private Random random;
    private ThreadGroup group;    
    public IndianPlayerThread(ThreadGroup group,String playerName) {
		this.group=group;
        this.playerName = playerName;
        this.random = new Random();
    }
        
    @Override
    public void run() {
            int score = random.nextInt(101); // Generate a random score between 0 and 100
            System.out.println(group.getName()+":"+playerName + " scored " + score + " runs!");
    }
}
public class ThreadGroupDemo{
    public static void main(String[] args) {
        ThreadGroup sunRisers = new ThreadGroup("SunRisers");

        // Creating and  adding the player threads to the IndianCricketTeam ThreadGroup 
        IndianPlayerThread viratKohliThread = new IndianPlayerThread(sunRisers,"Virat Kohli");
        IndianPlayerThread rohitSharmaThread = new IndianPlayerThread(sunRisers,"Rohit Sharma");
        IndianPlayerThread shikharDhawanThread = new IndianPlayerThread(sunRisers,"Shikhar Dhawan");
        
		viratKohliThread.start();
        rohitSharmaThread.start();
        shikharDhawanThread.start();

		
        ThreadGroup csk = new ThreadGroup("Chennai Super Kings");

        // Creating and  adding the player threads to the IndianCricketTeam ThreadGroup 
        IndianPlayerThread dhoniThread = new IndianPlayerThread(csk,"Dhoni");
        IndianPlayerThread ravindraThread = new IndianPlayerThread(csk,"Ravindra Jadeja");
        IndianPlayerThread rajThread = new IndianPlayerThread(csk,"Rajvardhan Hangargekar");
		
        
        dhoniThread.start();
        ravindraThread.start();
        rajThread.start();

        // Wait for all player threads to finish
        try {
            while (sunRisers.activeCount() > 0 && csk.activeCount()>0) {
                Thread.sleep(100); // Wait for a short time
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("Match simulation is over!");
    }
}

/*
D:\>javac ThreadGroupDemo.java

D:\>java ThreadGroupDemo
Match simulation is over!
Virat Kohli scored 54 runs!
Shikhar Dhawan scored 55 runs!
Rohit Sharma scored 99 runs!
*/
Code language: JavaScript (javascript)

Grouping threads in Java allows for more efficient management and coordination, especially when dealing with large numbers of threads that need to be organized or categorized for better control. This can be achieved using thread groups, which help in structuring and controlling sets of related threads. By grouping threads, developers can easily apply policies like pausing, resuming, or interrupting all threads in a group, or even handling exceptions collectively. Additionally, thread groups provide a way to manage resources more effectively, ensuring better scalability and robustness in applications.

Scroll to Top