问题描述

我正在Java 1.6中使用一个ExecutoreService,简单地开始

ExecutorService pool = Executors.newFixedThreadPool(THREADS).

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

pool.shutdown();

我可以避免通过某种方式将这个池使用的内部线程管理转换成deamon线程来调用吗?或者我在这里遗漏了一些东西。

最佳解决方案

大概最简单和最优的解决方案是在Marco13’s answer中,所以不要被投票差异(我的回答是几年前)或接受标记(这意味着我的解决方案适合于OP情况不是最好的)。


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

  1.  
    ExecutorService exec = Executors.newFixedThreadPool(4,
  2.  
    new ThreadFactory() {
  3.  
    public Thread newThread(Runnable r) {
  4.  
    Thread t = Executors.defaultThreadFactory().newThread(r);
  5.  
    t.setDaemon(true);
  6.  
    return t;
  7.  
    }
  8.  
    });
  9.  
     
  10.  
    exec.execute(YourTaskNowWillBeDaemon);

但是如果你想获得执行器,让它的任务完成,同时在应用程序完成后会自动调用它的shutdown()方法,你可能希望用Guava’s MoreExecutors.getExitingExecutorService来包装你的执行器。

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

次佳解决方案

已经有一个内置功能用于创建一个ExecutorService,在一段时间不活动后终止所有线程:您可以创建一个ThreadPoolExecutor,传递所需的时序信息,然后在此执行器服务上调用allowCoreThreadTimeout(true)

  1.  
    /**
  2.  
    * Creates an executor service with a fixed pool size, that will time
  3.  
    * out after a certain period of inactivity.
  4.  
    *
  5.  
    * @param poolSize The core- and maximum pool size
  6.  
    * @param keepAliveTime The keep alive time
  7.  
    * @param timeUnit The time unit
  8.  
    * @return The executor service
  9.  
    */
  10.  
    public static ExecutorService createFixedTimeoutExecutorService(
  11.  
    int poolSize, long keepAliveTime, TimeUnit timeUnit)
  12.  
    {
  13.  
    ThreadPoolExecutor e =
  14.  
    new ThreadPoolExecutor(poolSize, poolSize,
  15.  
    keepAliveTime, timeUnit, new LinkedBlockingQueue<Runnable>());
  16.  
    e.allowCoreThreadTimeOut(true);
  17.  
    return e;
  18.  
    }

EDIT Referring to the remarks in the comments: Note that this thread pool executor will not automatically shut down when the application exits. The executor will continue to run after the application exits, but no longer than the keepAliveTime. If, depending on the precise application requirements, the keepAliveTime has to be longer than a few seconds, the solution in the answer by Pshemo may be more appropriate: When the threads are set to be daemon threads, then they will end immediately when the application exits.

第三种解决方案

我会使用Guava的ThreadFactoryBuilder类。

ExecutorService threadPool = Executors.newFixedThreadPool(THREADS, new ThreadFactoryBuilder().setDaemon(true).build());

如果你还没有使用Guava,我会去一个ThreadFactory子类,如Pshemo’s answer顶部所述

第四种方案

是。

您只需创建自己的ThreadFactory类,即创建守护进程线程而不是常规线程。

参考文献

在Java中,将ExecutorService转为守护程序的更多相关文章

  1. 将java中Map对象转为有相同属性的类对象(json作为中间转换)

    java中Map对象转为有相同属性的类对象(json作为中间转换) 准备好json转换工具类 public class JsonUtil { private static ObjectMapper o ...

  2. Java 中的字符串转为二进制

    /** * 将字符串转为二进制 */ public class StrConversion { public static void main(String args[]) { String str ...

  3. java中list强转为map类型

    起因:读取数据库文件的测试用例,测试用例需要存放到一个map中,方便下次调用, 读取的内容返回的内容存放在一个list中,并且数据内容是key=value的形式,最开始使用切片方式,做了很多无用功,后 ...

  4. Java中ExecutorService和CompletionService区别

    我们现在在Java中使用多线程通常不会直接用Thread对象了,而是会用到java.util.concurrent包下的ExecutorService类来初始化一个线程池供我们使用. 之前我一直习惯自 ...

  5. java中ExecutorService接口

    一.声明 public interface ExecutorService extends Executor 位于java.util.concurrent包下 所有超级接口:Executor 所有已知 ...

  6. java中Executor、ExecutorService、ThreadPoolExecutor介绍(转)

    1.Excutor 源码非常简单,只有一个execute(Runnable command)回调接口 public interface Executor { /**     * Executes th ...

  7. java中把list列表转为arrayList以及arraylist数组截取的简单方法

    java中把list列表转为arrayList以及arraylist数组截取的简单方法 package xiaobai; import java.util.ArrayList; import java ...

  8. Java中数组转为List三种情况的优劣对比,常犯的类型转换错误原因解析

    一.最常见方式(未必最佳)通过 Arrays.asList(strArray) 方式,将数组转换List后,不能对List增删,只能查改,否则抛异常. 关键代码:List list = Arrays. ...

  9. java中Executor、ExecutorService、ThreadPoolExecutor介绍

    源码非常简单,只有一个execute(Runnable command)回调接口 public interface Executor { /**      * Executes the given c ...

随机推荐

  1. ButterKnife注解框架详解

    Android 懒人注解框架 :https://github.com/JakeWharton/butterknife 前言: 注解,相信很多同学都用到了,对控件进行初始化的时候需要用到 findVie ...

  2. Android为TV端助力 布局、绘制、内存泄露、响应速度、listview和bitmap、线程优化以及一些优化的建议!

    1.布局优化 首先删除布局中无用的控件和层级,其次有选择地使用性能较低的viewgroup,比如布局中既可以使用RelativeLayout和LinearLayout,那我们就采用LinearLayo ...

  3. listview reclyerview上下拉刷新

    x写控件挺麻烦的,因为有很多细节要处理好,列表控件使用太频繁了,网上也各种自定义的方法,一般的listview自定义肯定会联想到加个头部,然后监听事件加动画,其实方式很多种,今天记录的方式是另外一种方 ...

  4. 对display主要属性的探究,以及vertical-aligin

    display 首先要简单说明一下display的主要3个主要属性,分别为block,inline-block,inline,这里只提及主要,关于其他的inherit,none等可以自行了解 inli ...

  5. katalon之web文件上传

    参考:https://docs.katalon.com/katalon-studio/docs/webui-upload-file.html#example- 适用范围:tag=input, type ...

  6. Visual Studio Team Services Demo Generator简介

    Visual Studio Team Services Demo Generator简介 Visual Studio Team Services Demo Generator能够帮助我们在Visual ...

  7. 注入攻击(SQL注入防御)

    正确的防御SQL注入 sql注入的防御不是简单只做一些用户输入的escape处理,这样是不够的,只是提高了攻击者的门槛而已,还是不够安全. 例如 mysql_real_escape_string()函 ...

  8. 修改mysql默认端口

    最初,我将mysql端口改成了3307,现在需要将其改3306端口,已改好,做个记录 首先:借助资源监视器,找到对应的端口,查看对应的Pid,然后打开任务管理器,点击服务,找到对应的服务器,将其服务停 ...

  9. 06.Python网络爬虫之requests模块(2)

    今日内容 session处理cookie proxies参数设置请求代理ip 基于线程池的数据爬取 知识点回顾 xpath的解析流程 bs4的解析流程 常用xpath表达式 常用bs4解析方法 引入 ...

  10. python 协程、I/O模型

    一.引子 (超哥协程) 并发本质:保存状态+切换 cpu正在运行一个任务,转而执行另一个任务的情概况:1.是该任务发生了阻塞:2.该任务计算的时间过长或有一个优先级更高的程序替代了它. 协程本质上就是 ...