Sunday, 5 February 2012

ThreadGroup in Java

A thread group represents a set of threads. In addition, a thread group can also include other thread groups. The thread groups form a tree in which every thread group except the initial thread group(i.e. main) has a parent.Thread groups provide a mechanism for collecting multiple threads into a single object and manipulating those threads all at once, rather than individually.


If you not explicitly set the thread group during thread creation, the runtime system puts the new thread in some reasonable default group.

You cannot move a thread to a new group after the thread has been created.  
  
A thread is allowed to access information about its own thread group, but not to access information about its thread group's parent thread group or any other thread groups. 

The Default Thread Group



If you create a new Thread without specifying its group in the constructor, the runtime system automatically places the new thread in the same group as the thread that created it.


When a Java application first starts up, the Java runtime system creates a ThreadGroup named main. Unless specified otherwise, all new threads that you create become members of the main thread group.

Creating a Thread Explicitly in a Group

If you wish to put your new thread in a thread group other than the default, you must specify the thread group explicitly when you create the thread. The Thread class has three constructors that let you set a new thread's group:

public Thread(ThreadGroup group, Runnable target)
public Thread(ThreadGroup group,String name)
public Thread(ThreadGroup group, Runnable target,String name)

Each of these constructors creates a new thread within the specified thread group.See one example,


ThreadGroup group1 = new ThreadGroup("Threads Group1");
Thread thread1 = new Thread(group1, "a thread for group1");


java.lang.ThreadGroup class

Java thread groups are implemented by the ThreadGroup class in the java.lang package.

ThreadGroup object can be created using the following constructors


public ThreadGroup(String name)

Constructs a new thread group. The parent of this new group is the thread group of the currently running thread.The checkAccess method of the parent thread group is called with no arguments; this may result in a security exception.

public ThreadGroup(ThreadGroup parent,String name)
 
Creates a new thread group. The parent of this new group is the specified thread group.The checkAccess method of the parent thread group is called with no arguments; this may result in a security exception.

ThreadGroups can contain not only threads but also other ThreadGroups. The top-most thread group in a Java application is the thread group named main. You can create threads and thread groups in the main group. You can also create threads and thread groups in subgroups of main. The result is a root-like hierarchy of threads and thread groups:



No comments:

Post a Comment