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.
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 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());
}
}
Similar Java Tutorials
- Odd Even in Java
- Method to print exception information in Java
- Exception Handling by Using try-catch in Java
- Checked Exception vs Unchecked Exception
- Exception Hierarchy in Java
- Java Exception Handling Interview Questions
- final finally finalize in java
- User Defined Exception in Java
- Exception Handling Keyword in Java
- throw throws in Java
- try with multiple catch block in Java
- Threads in Java
- Thread priority in Java
- Threads communication in Java
- Daemon Thread in Java