Contents

ThreadGroup in Java

Writen by: David Vlijmincx

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.

1
2
3
4
5
6
7
Runnable task = () -> System.out.println(Thread.currentThread().getThreadGroup().getName());

ThreadGroup threadGroup = new ThreadGroup("group-name");

Thread t1 = new Thread(threadGroup, task);

t1.start();

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.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
Runnable task = () -> System.out.println(Thread.currentThread().getThreadGroup().getName());

ThreadGroup parentGroup = new ThreadGroup("parent-group-name");
ThreadGroup childGroup = new ThreadGroup(parentGroup,"child-group-name");

Thread t1 = new Thread(parentGroup, task);
Thread t2 = new Thread(childGroup, task);

t1.start();
t2.start();

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.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
Runnable task = () -> System.out.println(Thread.currentThread().getThreadGroup().getName());

ThreadGroup threadGroup = new ThreadGroup("group-name");
ThreadGroup childGroup = new ThreadGroup(threadGroup,"child-group-name");

Thread t1 = new Thread(threadGroup, task);
Thread t2 = new Thread(childGroup, task);

t1.start();
t2.start();

threadGroup.interrupt();

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.

Conclusion

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.

Further reading

More about multithreading in Java: