Thursday 25 July 2019

Thread Group

  • Thread groups offer a convenient way to manage groups of threads as a unit.
  • A thread is always a member of a thread group.
  • A thread group not only includes threads but also other thread groups.
  • 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:

public class ThreadGroupDemo {
  public static void main(String[] args) {
    Thread t1 = Thread.currentThread();

    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 thread group");

    ThreadGroup tg2 = t2.getThreadGroup();
    System.out.println("New  thread's name:  " + t2.getName());
    System.out.println("New  thread's  group  name:  " + tg2.getName());
  }
}
 
Output:
Current thread's  name: main
Current thread's  group  name: main
New  thread's name: my thread group
New  thread's  group  name: main
  • 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.

Thanks..!!

No comments:

Post a Comment