Java - Thread Thread Group

Introduction

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.

The JVM creates a thread group called main.

A thread group is represented by java.lang.ThreadGroup class.

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

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

Demo

public class Main {
  public static void main(String[] args) {
    // Get the current thread, which is called "main"
    Thread t1 = Thread.currentThread();

    // Get the thread group of the main thread
    ThreadGroup tg1 = t1.getThreadGroup();

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

    // Creates a new thread. Its thread group is the same that of the main thread.
    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());
  }/*from  w w w .j a v  a2  s .  c  o  m*/
}

Result

Related Topics