Executor and Daemon in Java

前端 未结 3 1943
北海茫月
北海茫月 2020-12-09 12:27

I have a MyThread object which I instantiate when my app is loaded through the server, I mark it as a Daemon thread and then call start() on it. The thread is m

相关标签:
3条回答
  • 2020-12-09 12:39

    If you're using a scheduled executor, you can provide a ThreadFactory. This is used to create new Threads, and you can modify these (e.g. make them daemon) as you require.

    EDIT: To answer your update, your ThreadFactory just needs to implement newThread(Runnable r) since your WebRunnable is a Runnable. So no real extra work.

    0 讨论(0)
  • 2020-12-09 12:46

    Just to complement with another possible solution for completeness. It may not be as nice though.

    final Executor executor = Executors.newSingleThreadExecutor();
    Runtime.getRuntime().addShutdownHook(new Thread() {
    
        @Override
        public void run() {
            executor.shutdownNow();
        }
    });
    
    0 讨论(0)
  • 2020-12-09 12:58

    Check out the JavaDoc for newSingleThreadScheduledExecutor(ThreadFactory threadFactory)

    It would be implemented something like this:

    public class MyClass { 
        private DaemonThreadFactory dtf = new DaemonThreadFactory();
        private ScheduledExecutorService executor = 
                                     Executors.newSingleThreadScheduledExecutor(dtf);
        // ....class stuff.....
        // ....Instance the runnable.....
        // ....submit() to executor....
    }
    
    class DaemonThreadFactory implements ThreadFactory {
        public Thread newThread(Runnable r) {
            Thread thread = new Thread(r);
            thread.setDaemon(true);
            return thread;
        }
    }
    
    0 讨论(0)
提交回复
热议问题