| All threads belong to a thread group. ThreadGroup, a java.lang class,
defines and implements the capabilities of a group of related threads. |
| |
| The ThreadGroup class manages groups of threads for Java applications.
A ThreadGroup can contain any number of threads. The threads in a
group are generally related in some way, such as who created them, what
function they perform, or when they should be started and stopped. |
| |
| 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". We can create
threads and thread groups in the "main" group. We can also
create threads and thread groups in subgroups of "main" and so on. |
| |
| The result is a root-like hierarchy of threads and thread groups. |
| |
|
| |
| The ThreadGroup class has methods that can be categorized as follows: |
| |
| 1. Collection management Method:-methods that manage
the collection of threads and subgroups contained in the thread group. |
| |
| 2. Method that Operate on the Group:-these methods set
or get attributes of the ThreadGroup object. |
| |
| 3. Method that Operate on All Threads within a Group --this
is a set of methods that perform some operation, such as start or
resume, on all the threads and subgroups within the ThreadGroup. |
| |
| 4. Access Restriction Methods:-ThreadGroup and Thread
allow the security manager to restrict access to threads based on group membership. |
| |
| |
| Collection Management Methods |
| The ThreadGroup provides a set of methods that manage the
threads and subgroups within the group and allow other objects
to query the ThreadGroup for information about its contents. |
| |
| For example, |
| You can call ThreadGroup's activeCount() method to
find out the number of active threads currently in the group.
The activeCount() method is often used with the enumerate() method
to get an array filled with references to all the active threads in a ThreadGroup. |
| |
| For example, |
| The listCurrentThreads() method
in the following
example fills an array with all of the active threads in
the current thread group and prints their names: |
| |
class EnumerateTest
{
void listCurrentThreads()
{
ThreadGroup currentGroup = Thread.currentThread().getThreadGroup();
int numThreads;
Thread[] listOfThreads;
numThreads = currentGroup.activeCount();
listOfThreads = new Thread[numThreads];
currentGroup.enumerate(listOfThreads);
for (int i = 0; i < numThreads; i++) {
System.out.println("Thread #" + i + " = " + listOfThreads[i].getName());
}
}
} |
| |