ThreadGroup:
Based on functionality we can group Threads into a single unit which is nothing but ThreadGroup i.e., ThreadGroup contains a group of Threads.
In addition to Threads, ThreadGroup also can contain some sub ThreadGroups.
The main advantage of maintain Threads in the form of ThreadGroup and we can perform common operations very easily.
- Every Thread in java belongs to some group.
- Main Thread belongs to MainGroup.
- Every ThreadGroup in java is the child group of SystemGroup either directly or indirectly.
- Hence SystemGroup acts as a root for al ThreadGroups in java. SystemGroup contains several system levels Threads like
- Finalizer
- Reference Handler
- Signal Dispatcher
- Attach Listener
Output:
main
system
ThreadGroup is a java class present in java.lang package and it is direct child class of Object.
Constructors:
creates a new ThreadGroup with the specifies the group name. The parent of this new group is the ThreadGroup of currently executing Thread.
creates new ThreadGroup with the specified group name. The parent of this new ThreadGroup is specified parent group.
Output:
main
First Group
Important methods of ThreadGroup class:
1. String getName(): returns name of the ThreadGroup
2. int getMaxPriority(): returns max priority of ThreadGroup
3. void setMaxPriority(int p): to set maximum priority of ThreadGroup. the default max priority is 10.
Threads in the ThreadGroup that already have higher priority won’t be affected but newly added Threads is maxPriority is applicable.
4. ThreadGroup getParent(): returns parent group of current Thread
5. void list(): it prints information of ThreadGroup to the console
6. int activeCount(): returns number of active Threads present in the ThreadGroup
7. int activeGroupCount(): returns number of active groups present in the current ThreadGroup.
8. int enumerate(Thread[] t): to copy all active Threads of this ThreadGroup into provided Thread array. In this case sub ThreadGroups also will be considered.
9. int enumerate(ThreadGroup[] g): to copy all active sub ThreadGroups into ThreadGroup array.
10. boolean isDaemon(): to check whether ThreadGroup is Daemon or not.
11. void setDaemon(boolean b): set the Daemon into true or false state.
12. void interrupt(): to interrupt all waiting or sleeping Threads present in the ThreadGroup.
13. void destroy(): to destroy ThreadGroup and its sub ThreadGroups.
Output:
Child Thread
Child Thread
2
1
java.lang.ThreadGroup[name=ParentGroup,maxpri=10]
Thread[ChildThread1,5,ParentGroup]
Thread[ChildThread2,5,ParentGroup]
java.lang.ThreadGroup[name=ChildGroup,maxpri=10]
0
1
java.lang.ThreadGroup[name=ParentGroup,maxpri=10]
java.lang.ThreadGroup[name=ChildGroup,maxpri=10]
write a program to display all active Threads name belongs to system group and its child groups.
Output:
Reference Handler ---- true
Finalizer ---- true
Signal Dispatcher ---- true
Attach Listener ---- true
Notification Thread ---- true
main ---- false
Common-Cleaner ---- true
0 Comments