Thursday 6 March 2014

Destroy Thread group

ThreadGroup class provides destroy method, to destroy a ThreadGroup, if the thread group empty. Empty mean, it don't have any active threads and all the sub groups also empty.

public final void destroy()
Destroys this thread group and all of its subgroups. This thread group must be empty, indicating that all threads that had been in this thread group have since stopped.

class GroupDestroyEx extends Thread{

 public void run(){
  try{
   Thread.currentThread().sleep(2000);
  }
  catch(Exception e){
  }
 }

 GroupDestroyEx(ThreadGroup grp, String name){
  super(grp, name);
 }

 public static void main(String args[])throws Exception{
  ThreadGroup group1 = new ThreadGroup("group1");
  ThreadGroup group2 = new ThreadGroup(group1, "group2");

  GroupDestroyEx thread1 = new GroupDestroyEx(group1, "thread1");
  GroupDestroyEx thread2 = new GroupDestroyEx(group1, "thread2");

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

  thread1.join();
  thread2.join();

  group1.destroy();
  System.out.println("Is group1 destroyed " + group1.isDestroyed());
  System.out.println("Is group1 destroyed " + group2.isDestroyed());
 }
}
   
Output
Is group1 destroyed true
Is group1 destroyed true

Some Points to Remember
1. IllegalThreadStateException thrown, when you tries to destroy a group, which has some active threads or active sub groups in it.
class GroupDestroyEx extends Thread{

 public void run(){
  try{
   Thread.currentThread().sleep(2000);
  }
  catch(Exception e){
  }
 }

 GroupDestroyEx(ThreadGroup grp, String name){
  super(grp, name);
 }

 public static void main(String args[])throws Exception{
  ThreadGroup group1 = new ThreadGroup("group1");
  ThreadGroup group2 = new ThreadGroup(group1, "group2");

  GroupDestroyEx thread1 = new GroupDestroyEx(group1, "thread1");
  GroupDestroyEx thread2 = new GroupDestroyEx(group1, "thread2");

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

  group1.destroy();

  System.out.println("Is group1 destroyed " + group1.isDestroyed());
  System.out.println("Is group1 destroyed " + group2.isDestroyed());
 }
}
   
Output
Exception in thread "main" java.lang.IllegalThreadStateException
  at java.lang.ThreadGroup.destroy(Unknown Source)
  at GroupDestroyEx.main(GroupDestroyEx.java:26)
   



Daemon Thread Group                                                 TimeUnit Class                                                 Home

No comments:

Post a Comment