Turning an ExecutorService to daemon in Java

后端 未结 8 2255
无人共我
无人共我 2020-11-27 02:39

I am using an ExecutoreService in Java 1.6, started simply by

ExecutorService pool = Executors.newFixedThreadPool(THREADS). 

When my main

8条回答
  •  Happy的楠姐
    2020-11-27 03:23

    You can use Guava's ThreadFactoryBuilder. I didn't want to add the dependency and I wanted the functionality from Executors.DefaultThreadFactory, so I used composition:

    class DaemonThreadFactory implements ThreadFactory {
        final ThreadFactory delegate;
    
        DaemonThreadFactory() {
            this(Executors.defaultThreadFactory());
        }
    
        DaemonThreadFactory(ThreadFactory delegate) {
            this.delegate = delegate;
        }
    
        @Override
        public Thread newThread(Runnable r) {
            Thread thread = delegate.newThread(r);
            thread.setDaemon(true);
            return thread;
        }
    }
    

提交回复
热议问题