ThreadGroup in Java


ThreadGroup in Java

In Java, ThreadGroup is a class that represents a group of threads. ThreadGroup provides a convenient way to organize and manage multiple threads as a single unit. Threads within a ThreadGroup share certain common characteristics and can be manipulated collectively.


Example 01:


package com.java.Multi_threading;

public class ThreadGroupExample {

public static void main(String[] args) {

// Create a ThreadGroup

ThreadGroup myGroup = new ThreadGroup("MyThreadGroup");


// Create threads within the ThreadGroup

Thread thread1 = new Thread(myGroup, new MyRunnable_1(), "Thread1");

Thread thread2 = new Thread(myGroup, new MyRunnable_1(), "Thread2");


// Start the threads

thread1.start();

thread2.start();


// Display information about the ThreadGroup

System.out.println("ThreadGroup Name: " + myGroup.getName());

System.out.println("Number of Threads in the ThreadGroup: " + myGroup.activeCount());


// Enumerate and display threads in the ThreadGroup

Thread[] threads = new Thread[myGroup.activeCount()];

myGroup.enumerate(threads);

for (Thread t : threads) {

System.out.println("Thread: " + t.getName());

}

}

}


class MyRunnable_1 implements Runnable {

@Override

public void run() {

System.out.println("Executing thread: " + Thread.currentThread().getName());

}

}

Post a Comment

0 Comments