Java ThreadGroup

A thread group in Java represents a set of threads. In addition, a thread group can also include other thread groups. The thread groups form a tree in which every thread group except the initial thread group has a parent. A thread is allowed to access information about its own thread group, but not to access information about its thread group’s parent thread group or any other thread groups. Basically, Java provides a convenient way to group multiple threads in a single object. In such way, we can suspend, resume or interrupt group of threads by a single method call.

ThreadGroup class signature:

public class ThreadGroup extends Object implements Thread.UncaughtExceptionHandler
 
Constructors of ThreadGroup class

There are only two constructors of ThreadGroup class.

No.

Constructor

Description

1)

ThreadGroup (String name)

Creates a thread group with given name.

2)

ThreadGroup (ThreadGroup parent, String name)

Creates a thread group with given parent group & name.

 

See the coding example below to demonstrate the use of ThreadGroup class.

ThreadGroupExpt.java

class CustomThread extends Thread {

CustomThread(ThreadGroup group, String name) {
super(group, name);
start();
}

public void run() {
Thread t = Thread.currentThread();
System.out.println(t.getName() + " starting.");
System.out.println("");
try {
Thread.sleep(1000);
}
catch (InterruptedException e) { }
System.out.println(t.getName() + " ending.");
}
}

public class ThreadGroupExpt {

public static void main(String[] args) {

//creating thread groups
ThreadGroup tg = new ThreadGroup("Parent");
ThreadGroup tgc = new ThreadGroup(tg, "Child");

//adding threads to thread groups
CustomThread t1 = new CustomThread(tg, "1st");
CustomThread t2 = new CustomThread(tg, "2nd");
CustomThread t3 = new CustomThread(tgc, "3rd");
CustomThread t4 = new CustomThread(tgc, "4th");

System.out.println("Number of active threads: " + tg.activeCount());
tg.list();
System.out.println("\nNumber of active thread groups: " + tg.activeGroupCount());
}
}

 

Output:

1st starting.
4th starting.

Number of active threads: 4
3rd starting.

java.lang.ThreadGroup[name=Parent,maxpri=10]
2nd starting.

Thread[1st,5,Parent]
Thread[2nd,5,Parent]
java.lang.ThreadGroup[name=Child,maxpri=10]

Thread[3rd,5,Child]
Thread[4th,5,Child]

Number of active thread groups: 1
4th ending.
1st ending.
3rd ending.
2nd ending.