What is a ThreadGroup?

Brandon Rohlfs

A ThreadGroup is used to represent a group of Threads. A tree structure can be formed from ThreadsGroups containing other ThreadGroups. Threads can only access the ThreadGroup to which they belong. This means that access to a ThreadGroups parent or other ThreadGroup is not permitted. Once a ThreadGroup is created various information can be obtained such as the ThreadGroups name, how many threads are active, the maximum priority that can be contained within the group and a host of other information.

The ThreadGroup class provides two constructors.

ThreadGroup(String name)
ThreadGroup(ThreadGroup parent, String name)
public class ThreadGroupTest{
 public static void main(String[] args){
  ThreadGroup squares = new ThreadGroup("Squares");
  Thread t1 = new Thread(squares, new T(), "t1"); 
  Thread t2 = new Thread(squares, new T(), "t2"); 
  System.out.println("ThreadGroup name is: " + squares.getName()); 
  System.out.println("There are currently " + squares.activeCount() + " threads running");
  System.out.println("The maximum priority of a Thread that can be contained                               
  within " + squares.getName() + " is " + squares.getMaxPriority()); 
  System.out.println("There are currently " + squares.activeGroupCount() + " active groups");
  System.out.println(squares.getName() + " parent is " +  squares.getParent()); 

class T implements Runnable{
 private int square; 
 public void run(){
  for(int i = 1; i < 5; i++){
   square = i * i; 
   System.out.println("Thread " + Thread.currentThread().getName() +
	" has a priority of " + Thread.currentThread().getPriority() +
	 ": " + square);   
About | Sitemap | Contact