Sunday 19 May 2013

how to make executor as daemon thread




You need to use a new ThreadFactory that creates daemon threads. See this answer here


import these classes:


import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;



Add this Class


static class DaemonThreadFactory implements ThreadFactory {
   public Thread newThread(Runnable r) {
       Thread thread = new Thread(r);
       thread.setDaemon(true);
       return thread;
   }
}


Use like this:

private static DaemonThreadFactory dtf = new DaemonThreadFactory();
private static ExecutorService service= Executors.newFixedThreadPool(5, dtf);


If you need any example on this please leave a comment i will reply.



--------------------------------


you can also use Anonumous class like this:

ExecutorService pool = Executors.newSingleThreadExecutor(new ThreadFactory() {
   @Override
   public Thread newThread(Runnable runnable) {
      Thread thread = Executors.defaultThreadFactory().newThread(runnable);
      thread.setDaemon(true);
      return thread;
   }
});



No comments:

Post a Comment

Please comment here