Thread Groups
The ThreadGroup class allows us
to deal with threads wholesale: we can use it to arrange threads in groups
and deal with the groups as a whole. A thread group can contain other
thread groups in addition to individual threads, so our arrangements can
be hierarchical. Thread groups are particularly useful when we want to
start a task that might create many threads of its own. By assigning the
task a thread group, we can later identify and control all the task’s
threads. Thread groups are also the subject of restrictions that can be
imposed by the Java Security Manager, so we can restrict a thread’s
behavior according to its thread group. For example, we can forbid threads
in a particular group from interacting with threads in other groups. This
is one way web browsers can prevent threads started by Java applets from
stopping important system threads.
When we create a thread, it normally becomes part of the thread group to which the currently running thread belongs. To create a new thread group of our own, we can call the constructor:
ThreadGroupmyTaskGroup=newThreadGroup("My Task Group");
The ThreadGroup constructor takes
a name, which a debugger can use to help you identify the group. (You can
also assign names to the threads themselves.) Once we have a group, we can
put threads in the group by supplying the ThreadGroup object as an argument to the
Thread constructor:
ThreadmyTask=newThread(myTaskGroup,taskPerformer);
Here, myTaskGroup is the thread group, and ...