Core java tutorial for beginners
A tutorial blog which explains different core concepts related to Java along with programming examples

February 17, 2016 Categories: Multithreading. No Comments on Thread Groups

In this article we will learn what is a thread group? How to work with thread groups in Java along with example program.

 

A thread group is a collection of threads. A thread group allows the programmer to maintain a group of threads more effectively. To support thread groups Java provides a class named ThreadGroup available in java.lang package.

 

Some of the constructors available in ThreadGroup class are:

ThreadGroup(String group-name)

ThreadGroup(ThreadGroup parent, String group-name)

 

After creating a thread group using one of the above constructors, we can add a thread to the thread group using one of the following Thread constructors:

Thread(ThreadGroup ref, Runnable obj)

Thread(ThreadGroup ref, String thread-name)

Thread(ThreadGroup ref, Runnable obj, String thread-name)

 

Following are some of the methods available in ThreadGroup class:

  • getName() – To get the name of the thread group
  • setMaxPriority() – To set the maximum priority of all the threads in the group
  • setMinPriority() – To set the minimum priority of all the threads in the group
  • start() – To start the execution of all the threads in the group
  • list() – To print information of the thread group and the threads in the group.

 

Below program demonstrates the use of thread groups in Java:

 

Output of the above program is:

First Thread belongs to the group: Group A
Maximum priority of Group A is: 8
Second Thread belongs to the group: Group A
Maximum priority of Group A is: 8
First Thread:1
Second Thread:1
First Thread:2
Second Thread:2
Second Thread:3
First Thread:3
All the threads in the group will be stopped
java.lang.ThreadGroup[name=Group A,maxpri=8]
Thread[First Thread,5,Group A]
Thread[Second Thread,5,Group A]

 

Related Links:

Note: Do you have a question on this article or have a suggestion to make this article better? You can ask or suggest us by filling in the below form. After commenting, your comment will be held for moderation and will be published in 24-48 hrs.

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll Up