What is a ThreadGroup
Using a ThreadGroup you can group threads. A ThreadGroup provides an easy way to manage and control them as a unit. A ThreadGroup can also be the child or parent of another ThreadGroup.
Creating a ThreadGroup
To create a new ThreadGroup you can instantiate a new instance using the constructor like is done on line 3 of the following example. This created a ThreadGroup with the name “group-name”.
The next step is to add threads to this group. To do this you create a new thread using the constructor and pass the group as a parameter. You can check line 5 of the next example of how this is done.
Parent-child thread group
ThreadGroup can also be the parent or a child of another ThreadGroup. In the following example, you see two ThreadGroup and the childGroup is a child of the parentGroup.
When you run this example you see that both threads print their own ThreadGroup name.
Interrupting all threads inside a group
Using the ThreadGroup you can control all the threads and child groups that belong to it. In the next example, on line 12, we interrupt all threads inside the parent and child group.
If you called the interrupt method on the child group only threads in the child group would have been interrupted. The threads belonging to the parent group would continue running.
The ThreadGroup class provides a way to group threads together, allowing you to manage and control them as a single group. You can create a ThreadGroup instance and add threads to it using the Thread constructor. By grouping threads, you can simplify the management and control of your multithreaded applications.
More about multithreading in Java: