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.
Constructors of ThreadGroup class
There are only two constructors of ThreadGroup class.
Important methods of ThreadGroup class
There are many methods in ThreadGroup class. A list of important 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.
one two three Thread Group Name: Parent ThreadGroup java.lang.ThreadGroup[name=Parent ThreadGroup,maxpri=10] Thread[one,5,Parent ThreadGroup] Thread[two,5,Parent ThreadGroup] Thread[three,5,Parent ThreadGroup]