Home »
Java »
Java Programs
Java program to destroy a thread group
Java example to destroy a thread group.
Submitted by Nidhi, on April 10, 2022
Problem statement
In this program, we will create a thread group using ThreadGroup class and add child threads to the group and destroy the thread group using destroy() method.
Java program to destroy a thread group
The source code to destroy a thread group is given below. The given program is compiled and executed successfully.
// Java program to destroy a thread group
class MyThread extends Thread {
MyThread(String threadname, ThreadGroup tg) {
super(tg, threadname);
start();
}
public void run() {
try {
Thread.sleep(100);
System.out.println(Thread.currentThread().getName() + " is finshed");
} catch (Exception e) {
System.out.println(e);
}
}
}
public class Main {
public static void main(String[] args) {
try {
ThreadGroup group = new ThreadGroup("Parent thread");
MyThread t1 = new MyThread("Child Thread1", group);
System.out.println(t1.getName() + " is started");
MyThread t2 = new MyThread("Child Thread2", group);
System.out.println(t2.getName() + " is started");
t1.join();
t2.join();
group.destroy();
System.out.println(group.getName() + " destroyed");
} catch (Exception e) {
System.out.println(e);
}
}
}
Output
Total active threads: 3
Child Thread2 is running
Child Thread1 is running
Child Thread3 is running
Explanation
In the above program, we created two classes MyThread and Main. We created MyThread class by extending the Thread class.
The Main class contains a main() method. The main() method is the entry point for the program. Here, we created an object of ThreadGroup class and added the child thread into the thread group. After that, we destroyed the thread group using destroy() method.
Java Threading Programs »