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]

Our Services:

Java Training | Python Training | Machine Learning with Python Training | Deep Learning with Python Training | Data Science with Python Training | Projects

Silansoftware Pvt.Ltd, BBSR
Call to: 0674-2361252