在Java中将ExecutorService转换为守护进程 [英] Turning an ExecutorService to daemon in Java

查看:450
本文介绍了在Java中将ExecutorService转换为守护进程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Java 1.6中使用ExecutoreService,只需通过

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

ExecutorService pool = Executors.newFixedThreadPool(THREADS). 

当我的主线程完成时(以及线程池处理的所有任务),这个池将阻止我的程序关闭,直到我明确调用

When my main thread is finished (along with all the tasks processed by the thread pool), this pool will prevent my program from shutting down until I explicitly call

pool.shutdown();

我是否可以通过某种方式将此池中使用的内部线程管理变为deamon来避免线?或者我在这里遗漏了一些东西。

Can I avoid having to call this by somehow turning the internal thread managing used by this pool into a deamon thread? Or am I missing something here.

推荐答案

可能最简单和首选的解决方案是 Marco13的答案所以不要被投票差异所欺骗(我的回答是几年之久)或接受标记(它只是意味着我的解决方案适合OP情况而不是它最好)。

Probably simplest and preferred solution is in Marco13's answer so don't get fooled by vote difference (mine answer is few years older) or acceptance mark (it just means that mine solution was appropriate for OP circumstances not that it is best).

您可以使用 ThreadFactory 来设置线程在Executor里面给守护进程。这将影响执行程序服务,它也将成为守护程序线程,因此如果没有其他非守护程序线程,它(以及由它处理的线程)将停止。这是一个简单的例子:

You can use ThreadFactory to set threads inside Executor to daemons. This will affect executor service in a way that it will also become daemon thread so it (and threads handled by it) will stop if there will be no other non-daemon thread. Here is simple example:

ExecutorService exec = Executors.newFixedThreadPool(4,
        new ThreadFactory() {
            public Thread newThread(Runnable r) {
                Thread t = Executors.defaultThreadFactory().newThread(r);
                t.setDaemon(true);
                return t;
            }
        });

exec.execute(YourTaskNowWillBeDaemon);






但如果你想获得遗嘱执行人任务完成,同时在应用程序完成时自动调用其 shutdown()方法,您可能希望用番石榴 MoreExecutors。 getExitingExecutorService


But if you want to get executor which will let its task finish, and at the same time will automatically call its shutdown() method when application is complete, you may want to wrap your executor with Guava's MoreExecutors.getExitingExecutorService.

ExecutorService exec = MoreExecutors.getExitingExecutorService(
        (ThreadPoolExecutor) Executors.newFixedThreadPool(4), 
        100_000, TimeUnit.DAYS//period after which executor will be automatically closed
                             //I assume that 100_000 days is enough to simulate infinity
);
//exec.execute(YourTask);
exec.execute(() -> {
    for (int i = 0; i < 3; i++) {
        System.out.println("daemon");
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
});

这篇关于在Java中将ExecutorService转换为守护进程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆