ThreadGroup in Java
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.
Note: Now suspend(), resume() and stop() methods are deprecated.
Java thread group is implemented by java.lang.ThreadGroup class.
A ThreadGroup represents a set of threads. A thread group can also include the other thread group. The thread group creates 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 it cannot access the information about its thread group's parent thread group or any other thread groups.
Constructors of ThreadGroup class
There are only two constructors of ThreadGroup class.
|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 and name.|
Methods of ThreadGroup class
There are many methods in ThreadGroup class. A list of ThreadGroup methods are given below.
||Modifier and Type
||This method determines if the currently running thread has permission to modify the thread group.
||This method returns an estimate of the number of active threads in the thread group and its subgroups.
||This method returns an estimate of the number of active groups in the thread group and its subgroups.
||This method destroys the thread group and all of its subgroups.
||This method copies into the specified array every active thread in the thread group and its subgroups.
||This method returns the maximum priority of the thread group.
||This method returns the name of the thread group.
||This method returns the parent of the thread group.
||This method interrupts all threads in the thread group.
||This method tests if the thread group is a daemon thread group.
||This method changes the daemon status of the thread group.
||This method tests if this thread group has been destroyed.
||This method prints information about the thread group to the standard output.
||This method tests if the thread group is either the thread group argument or one of its ancestor thread groups.
||This method is used to suspend all threads in the thread group.
||This method is used to resume all threads in the thread group which was suspended using suspend() method.
||This method sets the maximum priority of the group.
||This method is used to stop all threads in the thread group.
||This method returns a string representation of the Thread group.
Let's see a code to group multiple threads.
Now all 3 threads belong to one group. Here, tg1 is the thread group name, MyRunnable is the class that implements Runnable interface and "one", "two" and "three" are the thread names.
Now we can interrupt all threads by a single line of code only.
Thread Group Name: Parent ThreadGroup