Java ThreadGroup group threads into a group

Introduction

Java can group the threads.

Then we can treat the threads of a group as a single unit.

Java provides the ThreadGroup class to work with groups of threads.

A ThreadGroup object can be formed by Thread objects and by another ThreadGroup object, generating a tree structure of threads.

ThreadGroup class stores the Thread objects and the other ThreadGroup objects associated with it.

It can access all of their information and perform operations over all its members.


import java.util.concurrent.TimeUnit;

import java.util.Date;
import java.util.Random;

public class Main {
  public static void main(String[] args) {
    // Create a ThreadGroup
    ThreadGroup threadGroup = new ThreadGroup("My Group");
    Result result = new Result();

    // Create a SeachTask and 10 Thread objects with this Runnable
    MyThread searchTask = new MyThread(result);
    for (int i = 0; i < 5; i++) {
      Thread thread = new Thread(threadGroup, searchTask);
      thread.start();//ww w .  j  a v  a 2s.c o  m
      try {
        TimeUnit.SECONDS.sleep(1);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    }

    // Write information about the ThreadGroup to the console
    System.out.printf("Number of Threads: %d\n", threadGroup.activeCount());
    System.out.printf("Information about the Thread Group\n");
    threadGroup.list();

    // Write information about the status of the Thread objects to the console
    Thread[] threads = new Thread[threadGroup.activeCount()];
    threadGroup.enumerate(threads);
    for (int i = 0; i < threadGroup.activeCount(); i++) {
      System.out.printf("Thread %s: %s\n", threads[i].getName(), threads[i].getState());
    }

    // Wait for the finalization of the Threads
    waitFinish(threadGroup);

    // Interrupt all the Thread objects assigned to the ThreadGroup
    threadGroup.interrupt();
  }

  /**
   * Method that waits for the finalization of one of the ten Thread objects
   * assigned to the ThreadGroup
   * 
   * @param threadGroup
   */
  private static void waitFinish(ThreadGroup threadGroup) {
    while (threadGroup.activeCount() > 9) {
      try {
        TimeUnit.SECONDS.sleep(1);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    }
  }

}

class Result {
  private String name;

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }

}
class MyThread implements Runnable {

  private Result result;

  public MyThread(Result result) {
    this.result = result;
  }

  @Override
  public void run() {
    String name = Thread.currentThread().getName();
    System.out.printf("Thread %s: Start\n", name);
    try {
      doTask();
      result.setName(name);
    } catch (InterruptedException e) {
      System.out.printf("Thread %s: Interrupted\n", name);
      return;
    }
    System.out.printf("Thread %s: End\n", name);
  }

  /**
   * Method that simulates the search operation
   * 
   */
  private void doTask() throws InterruptedException {
    Random random = new Random((new Date()).getTime());
    int value = (int) (random.nextDouble() * 100);
    System.out.printf("Thread %s: %d\n", Thread.currentThread().getName(), value);
    TimeUnit.SECONDS.sleep(value);
  }

}



PreviousNext

Related