Thread Group in Java

In Java based on functionalities, we can group threads into a single unit which is known as Thread group that is thread group contain group of Thread. In addition to Threads, thread groups can also contain sub-thread groups.

In addition to threads, the group can also contain sub-thread groups.

The main advantage of maintaing Threads in the form of Thread group is we can perform common operations on all Threads very easily.

Every Thread in Java belongs to some group, The main Thread belongs to the main group. every Thread group in Java is the child group of the system group either directly or indirectly. Hence system group acts as a root for all Thread groups in Java. system group contains several system-level threads like finalizer, reference handler, Signal dispatcher, and Attach listener.

Thread Groups in Java

A thread group is a Java class present in java.lang package.

public class ThreadGroupExamp {
    public static void main(String[] args) {
        System.out.println(Thread.currentThread().getThreadGroup().getName());
        System.out.println(Thread.currentThread().getThreadGroup().getParent().getName());
    }
}
Thread Groups in Java

Thread Group Constructor

Syntax

 ThreadGroup group = new ThreadGroup(String name);

Example

 ThreadGroup group = new ThreadGroup("TheCodeData");

This constructor is used to create a new Thread group with a specified group name. The parent of this new group is the Thread group of the current executing Threads.

Syntax

 ThreadGroup group = new ThreadGroup(ThreadGroup parentGroup,String name);

Example

 ThreadGroup group2 = new ThreadGroup(group, "TheCodeData2");

This constructor is used to create a new Thread group with a specified group name. The parent of this new group is the specified parent group.

public class ThreadGroupExamp {
    public static void main(String[] args) {
        ThreadGroup group = new ThreadGroup("TheCodeData");
        System.out.println(group.getParent().getName());
        ThreadGroup group2 = new ThreadGroup(group,"TheCodeData2");
        System.out.println(group2.getParent().getName());
    }
}
ThreadGroup Constructor

Similar Java Tutorials

Leave a Comment