All About Class ThreadGroup in Java



A ThreadGroup is a set or collection of  threads. We can include different threads and ThreadGroups in a single ThreadGroup. so a ThreadGroup can contain several threads and ThreadGroups as its member elements. In that case it will form a tree structure popularly known as thread tree. In the thread tree every thread and ThreadGroup will have a parent except the initial ThreadGroup .A thread can access it's own ThreadGroup but not other ThreadGroup .

In java there is a default ThreadGroup called SystemThreadGroup. When a java application is started , the java runtime creates the main thread group as a member of SystemThreadGroup.A main thread is created in main thread group to run the main() method of the application.

Every thread instance is a member of exactly one thread group.By default all new threads and thread groups created when objects are instanciated will become the member of the main thread group.All thredas in an application will form a tree with the SystemThreadGroup as root.

The structure of the ThreadGroup class is as follows:

public class java.lang.ThreadGroup extends java.lang.Object{
//constructors
public ThreadGroup(String name)
//constructs a new ThreadGroup whose parent is the ThreadGroup of the currently running thread.
public ThreadGroup(ThreadGroup parent,String name);
//constructs a ThreadGroup whose parent is provided in the argument and it can throw NullPointerException if the ThreadGroup argument is null. It can also throw SecurityException if the current thread can not create a thread in the specified ThreadGroup.
//Methods:
public int activeCount();
public int activeGroupCount();
public final void checkAccess();
public final void destroy();
public int enumerate(Thread list[]);
public int enumerate(Thread list[],boolean recurse);
public int enumerate(ThreadGroup list[]);
public int enumerate(ThreadGroup list[],boolean recurse);
public final void resume();
public final void setDeamon(boolean deamon);
public final void setMaxPriority(int priority);
public final void stop();
public final void suspend();
public final int getMaxPriority();
public final String getName();
public final ThreadGroup getParent();
public final boolean isDeamon();
public void list();
public final boolean parentOf(ThreadGroup group);
public void UncaughtException(Thread t,Throwable e);
public String toString();
}
 
Below is an example how to create a thread and assign it to the thread group:

ThreadGroup tg=new ThreadGroup();
//creates a  new ThreadGroup 
Thread t=new Thread(tg);
// creates a thread in tg ThreadGroup as a member.
 
All About Class ThreadGroup in Java All About Class ThreadGroup in Java Reviewed by Animesh Chatterjee on September 18, 2018 Rating: 5

No comments:

Powered by Blogger.