Java Thread Tutorial - Java Thread Group








A thread is always a member of a thread group.

By default, the thread group of a thread is the group of its creator thread.

A thread group in a Java program is represented by an object of the java.lang.ThreadGroup class.

The getThreadGroup() method from the Thread class returns the reference to the ThreadGroup of a thread.

Example

The following code demonstrates that, by default, a new thread is a member of the thread group of its creator thread.

public class Main {
  public static void main(String[] args) {
    Thread t1 = Thread.currentThread();// www .  j  a v  a2s .co m

    ThreadGroup tg1 = t1.getThreadGroup();

    System.out.println("Current thread's  name:  " + t1.getName());
    System.out.println("Current thread's  group  name:  " + tg1.getName());

    Thread t2 = new Thread("my  new thread");

    ThreadGroup tg2 = t2.getThreadGroup();
    System.out.println("New  thread's name:  " + t2.getName());
    System.out.println("New  thread's  group  name:  " + tg2.getName());
  }
}

The code above generates the following result.





Note

You can also create a thread group and place a new thread in that thread group.

To place a new thread in your thread group, we must use one of the constructors of the Thread class that accepts a ThreadGroup object as an argument.

The following code places a new thread in a particular thread group:

ThreadGroup  myGroup = new ThreadGroup("My Thread  Group");
Thread  t = new Thread(myGroup,  "myThreadName");

Thread groups are arranged in a tree-like structure. A thread group can contain another thread group.

The getParent() method from the ThreadGroup class returns the parent thread group of a thread group.

The parent of the top-level thread group is null.

The activeCount() method from the ThreadGroup returns an estimate of the number of active threads in the group.

The enumerate() method of the ThreadGroup class returns the threads in a thread group.