Thread Group in Java

In this tutorial, we will see Thread Group in Java. Before reading, I would recommend reading Multithreading in Java, and Thread Priority and Daemon Thread

What is Thread Group in Java?

As the name signifies Thread Group in Java creates a group of threads.

In an enterprise application when you have uncountable threads then you should design ThreadGroups in order to manage a set of threads as a single unit.

Using ThreadGroups in Java, you can group multiple threads into a single object.

In this way, managing of threads is very easy because you can perform a certain task by calling a single method on thread group.

As Oracle stated, a thread group can also include other thread groups. The thread groups create a tree structure in which every thread group except the initial thread group has a parent.

Important:

If a thread is in a thread group then it is allowed to access information about its own thread group.

However, it can’t access information about its thread group’s parent or any other thread groups in the same thread group. (Read it again)

Now, let’s see some code example to group multiple threads into a thread group.

ThreadGroup threadGroup1 = new ThreadGroup("Thread Group One");

Thread thread1 = new Thread(threadGroup1, "one");
Thread thread2 = new Thread(threadGroup1, "two");
Thread thread3 = new Thread(threadGroup1, "three");

Here, thread named as “one”, “two”, “three” is assigned to single thread group i.e “Thread Group One”.

2. Thread Group Example:

Example1:

public class ThreadGroupExample extends Thread {

	public void run() {
		System.out.println("Start...");
	}

	public static void main(String[] args) {

		ThreadGroup threadGroup1 = new ThreadGroup("TG One");

		Thread thread1 = new Thread(threadGroup1, "one");
		Thread thread2 = new Thread(threadGroup1, "two");

		thread1.start();
		thread2.start();
		
		System.out.println("Running thread " + thread1.getName() + " of Thread Group : "
				+ thread1.getThreadGroup().getName());
		
	}
}

In below code, we will use thread group inside another thread group.

Example2:

ThreadGroup threadGroup1 = new ThreadGroup("Thread Group One");
ThreadGroup threadGroup2 = new ThreadGroup(threadGroup1, "Thread Group Two");

Thread thread1 = new Thread(threadGroup1, "one");
Thread thread2 = new Thread(threadGroup2, "two");

thread1.start();
thread2.start();

I hope you understood What is Thread Group in Java. To understand better. Keep practising.