Monday, February 20, 2017

ThreadGroup In Java

ThreagGroup is a class in java which is used to group the set of threads. In this way we can perform a common type of tasks to all threads at one shot like interrupting them all.
As a real example providing training to multiple students one by one for same course is not advisable, instead group them up and teach them in a class room only once.

Example:
package dev21century.threading;
//thread 1 class
class GThread1 implements Runnable
{
       //run method is the main code of thread
       public void run()
       {
         for(int i = 0;i<5;i++)
          {
           System.out.println("Thread Name: " + Thread.currentThread().getName());
          }
       }
}
//thread 2 class
class GThread2 implements Runnable
{
       public void run()
       {
        for(int i = 0;i<7;i++)
         {
          System.out.println("Thread Name: " + Thread.currentThread().getName());
         }
       }
}

//thread 3 class
class GThread3 implements Runnable
{
       public void run()
       {
        for(int i = 0;i<9;i++)
         {
          System.out.println("Thread Name: " + Thread.currentThread().getName());
         }
       }
}

public class MainThread {

       public static void main(String[] args) {

        ThreadGroup threadGroup = new ThreadGroup("MyThreadGroup");

        Thread gthread1 = new Thread(threadGroup, new GThread1());
        Thread gthread2 = new Thread(threadGroup, new GThread2());
        Thread gthread3 = new Thread(threadGroup, new GThread3());
       
        threadGroup.interrupt();
        /*with this statement, all 3 threads will
        be interrupetd at once.*/
       
        gthread1.start();
        gthread2.start();
        gthread3.start();

        for(int i = 0;i<11;i++)
        {
          System.out.println(Thread.currentThread().getName());
        }            
     }

}

Output:
main
main
Thread Name: Thread-2
Thread Name: Thread-2
Thread Name: Thread-2
Thread Name: Thread-2
Thread Name: Thread-1
Thread Name: Thread-2
main
Thread Name: Thread-0
main
Thread Name: Thread-2
Thread Name: Thread-1
Thread Name: Thread-2
main
Thread Name: Thread-0
main
Thread Name: Thread-2
Thread Name: Thread-1
Thread Name: Thread-2
main
main
main
main
Thread Name: Thread-0
main
Thread Name: Thread-1
Thread Name: Thread-1
Thread Name: Thread-1
Thread Name: Thread-1
Thread Name: Thread-0
Thread Name: Thread-0


No comments:

Post a Comment