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
ThreadGroup can contain other
ThreadGroups, 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 of the task’s threads.
ThreadGroups 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 that 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 ThreadGroup that the currently running
thread belongs to. To create a new ThreadGroup of
our own, we can call the constructor:
ThreadGroup myTaskGroup = new ThreadGroup("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:
Thread myTask = new Thread( myTaskGroup, taskPerformer );
Here, myTaskGroup is the thread group, ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access