ThreadGroup in Java

Naveen AnamaneniUpdated · 3 min read

A ThreadGroup in Java is an object that groups threads together, so they can be handled as a set: for example, to count them, list them or interrupt them all at once. Every thread belongs to a group; threads started from main belong to the group named main. ThreadGroup dates from Java 1.0 and is now considered legacy: many of its methods are deprecated or do nothing, and modern code manages related threads with executors instead. In this lesson, you will learn what ThreadGroup does so you can recognize it in older code.

Declaration

Declaration
public class ThreadGroup implements Thread.UncaughtExceptionHandler

Methods

MethodDescription
new ThreadGroup(String name)It is used to create a group inside the current thread's group.
new Thread(group, task, name)It creates a thread in a group.
getName(), getParent()It returns the group's name and its parent group.
activeCount()It estimates the number of live threads in the group.
enumerate(Thread[] list)It copies the live threads into an array.
interrupt()It interrupts every thread in the group.

Example: Grouping Worker Threads

Let's see an example that puts three workers in one group and interrupts them together.

Groups.java▶ Try it
public class Groups {
    public static void main(String[] args) throws InterruptedException {
        ThreadGroup downloads = new ThreadGroup("downloads");
        Thread[] workers = new Thread[3];
        String[] names = {"navika", "srihitha", "advitha"};
 
        for (int i = 0; i < 3; i++) {
            workers[i] = new Thread(downloads, () -> {
                try {
                    Thread.sleep(10_000);
                } catch (InterruptedException e) {
                    // stop quietly
                }
            }, "dl-" + names[i]);
            workers[i].start();
        }
 
        System.out.println("Group: " + downloads.getName()
            + ", parent: " + downloads.getParent().getName());
        System.out.println("Active threads: " + downloads.activeCount());
 
        downloads.interrupt();
        for (Thread t : workers) {
            t.join();
        }
        System.out.println("Active after interrupt: "
            + downloads.activeCount());
    }
}
Output
Group: downloads, parent: main
Active threads: 3
Active after interrupt: 0

Explanation: The group downloads is created inside the main group. Each worker is created in the group and sleeps for ten seconds. downloads.interrupt() interrupts all three at once, so they stop early, and after joining, no threads are active in the group.

Why ThreadGroup Is Legacy

  • Methods such as stop, suspend, resume, destroy and setDaemon are deprecated or removed.
  • activeCount and enumerate are only estimates.
  • Executors offer better grouping: shutdownNow() interrupts all their tasks, and they also reuse threads, collect results and handle errors.

Common Mistakes

Using ThreadGroup to manage work in new code. Use executors.

Trusting activeCount() as an exact number. Threads can start or end while it counts.

Practice

  1. Easy: Print the name of the thread group of the main thread using Thread.currentThread().getThreadGroup().
  2. Harder: Rewrite the example without ThreadGroup, keeping the threads in a List and interrupting each one.

Quick check: ThreadGroup

4 questions
1Which group do threads started from main belong to by default?
2What does group.interrupt() do?
3Is ThreadGroup recommended for new code?
4Is activeCount() exact?

Key Takeaways

Was this tutorial helpful?

Lesson 391 of 482