❮ Previous Next ❯

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.
Thread.currentThread().getThreadGroup().interrupt(); 

ThreadGroup Example

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

 

 

 

 

❮ Previous Next ❯




Warning: include(../footer1.php): failed to open stream: No such file or directory in /home/java8s/public_html/java/thread_group_java.php on line 166

Warning: include(../footer1.php): failed to open stream: No such file or directory in /home/java8s/public_html/java/thread_group_java.php on line 166

Warning: include(): Failed opening '../footer1.php' for inclusion (include_path='.:/opt/cpanel/ea-php56/root/usr/share/pear') in /home/java8s/public_html/java/thread_group_java.php on line 166