Java Design Pattern
Introduction to Java 10
Introduction to Java 11
Introduction to Java 12

ThreadGroup in Java

It is possible that we can group multiple threads in a single object. Here , we can suspend, resume or interrupt group of threads by a single method call.

Now suspend(), resume() and stop() methods are deprecated.

Java thread group is implemented by java.lang.ThreadGroup class.
Let's see a code to group multiple threads.

  1. ThreadGroup tg = new ThreadGroup("Group A");
  2. Thread t1 = new Thread(tg,new MyRunnable(),"one");
  3. Thread t2 = new Thread(tg,new MyRunnable(),"two");
  4. Thread t3 = new Thread(tg,new MyRunnable(),"three");

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
public class ThreadGroupExample implements Runnable{   
public void run(){   
	   public  static  void main(String[] args) 
		  ThreadGroupExample obj = new ThreadGroupExample();   
		  ThreadGroup tg = new ThreadGroup("Parent ThreadGroup");   
		  Thread t1 = new Thread(tg, obj,"one");   
		  Thread t2 = new Thread(tg, obj,"two");   
		  Thread t3 = new Thread(tg, obj,"three");   
		  System.out.println("Thread Group Name: "+tg1.getName());   


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]

About the Author

Silan Software is one of the India's leading provider of offline & online training for Java, Python, AI (Machine Learning, Deep Learning), Data Science, Software Development & many more emerging Technologies.

We provide Academic Training || Industrial Training || Corporate Training || Internship || Java || Python || AI using Python || Data Science etc