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. 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. There are only two constructors of ThreadGroup class.
There are many methods in ThreadGroup class. A list of ThreadGroup methods are given below.
|
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.
ThreadGroup Example
File: ThreadGroupDemo.java
Output: