Wednesday 5 March 2014

Daemon Thread Group

public final void setDaemon(boolean daemon)
If the parameter daemon is set to true, then changes the daemon status of this thread group. A daemon thread group is automatically destroyed when its last thread is stopped or its last thread group is destroyed.

If the thread group is not daemon, then the group is not destroyed even when its last thread stopped. A daemon thread group can contain daemon and Non daemon threads in it.

Example
class DaemonGroupEx extends Thread{
 DaemonGroupEx(ThreadGroup grp, String name){
  super(grp, name);
 }

 public void run(){
  Thread local = Thread.currentThread();
  System.out.println(local.getName() + " is daemon " + local.isDaemon());
 }

 public static void main(String args[])throws Exception{
  ThreadGroup group1 = new ThreadGroup("group1");
  DaemonGroupEx t1 = new DaemonGroupEx(group1, "thread1");
  t1.start();
  t1.join();
  System.out.println("Is group1 destroyed " + group1.isDestroyed());
 }
}

Output
thread1 is daemon false
Is group1 destroyed false

A daemon thread group is automatically destroyed when its last thread is stopped or its last thread group is destroyed.

Example
class DaemonGroupEx extends Thread{
 DaemonGroupEx(ThreadGroup grp, String name){
  super(grp, name);
 }

 public void run(){
  Thread local = Thread.currentThread();
  System.out.println(local.getName() + " is daemon " + local.isDaemon());
 }

 public static void main(String args[])throws Exception{
  ThreadGroup group1 = new ThreadGroup("group1");
  group1.setDaemon(true);

  DaemonGroupEx t1 = new DaemonGroupEx(group1, "thread1");
  t1.start();
  t1.join();

  System.out.println("Is group1 destroyed " + group1.isDestroyed());
 }
}

Output  
thread1 is daemon false
Is group1 destroyed true

   
Related Posts



Interrupt Thread Group                                                 Destroy Thread Group                                                 Home

No comments:

Post a Comment