在Java中,将ExecutorService转为守护程序
问题描述
我正在Java 1.6中使用一个ExecutoreService,简单地开始
ExecutorService pool = Executors.newFixedThreadPool(THREADS).
当我的主线程完成(以及由线程池处理的所有任务)时,此池将阻止我的程序关闭,直到我明确地调用
pool.shutdown();
我可以避免通过某种方式将这个池使用的内部线程管理转换成deamon线程来调用吗?或者我在这里遗漏了一些东西。
最佳解决方案
大概最简单和最优的解决方案是在Marco13’s answer中,所以不要被投票差异(我的回答是几年前)或接受标记(这意味着我的解决方案适合于OP情况不是最好的)。
您可以使用ThreadFactory将Executor中的线程设置为守护程序。这将影响执行器服务,它也将成为守护进程线程,因此如果没有其他non-daemon线程,它(以及由其处理的线程)将停止。这是一个简单的例子:
- 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()方法,你可能希望用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();
- }
- }
- });
次佳解决方案
已经有一个内置功能用于创建一个ExecutorService,在一段时间不活动后终止所有线程:您可以创建一个ThreadPoolExecutor,传递所需的时序信息,然后在此执行器服务上调用allowCoreThreadTimeout(true):
- /**
- * Creates an executor service with a fixed pool size, that will time
- * out after a certain period of inactivity.
- *
- * @param poolSize The core- and maximum pool size
- * @param keepAliveTime The keep alive time
- * @param timeUnit The time unit
- * @return The executor service
- */
- public static ExecutorService createFixedTimeoutExecutorService(
- int poolSize, long keepAliveTime, TimeUnit timeUnit)
- {
- ThreadPoolExecutor e =
- new ThreadPoolExecutor(poolSize, poolSize,
- keepAliveTime, timeUnit, new LinkedBlockingQueue<Runnable>());
- e.allowCoreThreadTimeOut(true);
- return e;
- }
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, thekeepAliveTimehas 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转为守护程序的更多相关文章
- 将java中Map对象转为有相同属性的类对象(json作为中间转换)
java中Map对象转为有相同属性的类对象(json作为中间转换) 准备好json转换工具类 public class JsonUtil { private static ObjectMapper o ...
- Java 中的字符串转为二进制
/** * 将字符串转为二进制 */ public class StrConversion { public static void main(String args[]) { String str ...
- java中list强转为map类型
起因:读取数据库文件的测试用例,测试用例需要存放到一个map中,方便下次调用, 读取的内容返回的内容存放在一个list中,并且数据内容是key=value的形式,最开始使用切片方式,做了很多无用功,后 ...
- Java中ExecutorService和CompletionService区别
我们现在在Java中使用多线程通常不会直接用Thread对象了,而是会用到java.util.concurrent包下的ExecutorService类来初始化一个线程池供我们使用. 之前我一直习惯自 ...
- java中ExecutorService接口
一.声明 public interface ExecutorService extends Executor 位于java.util.concurrent包下 所有超级接口:Executor 所有已知 ...
- java中Executor、ExecutorService、ThreadPoolExecutor介绍(转)
1.Excutor 源码非常简单,只有一个execute(Runnable command)回调接口 public interface Executor { /** * Executes th ...
- java中把list列表转为arrayList以及arraylist数组截取的简单方法
java中把list列表转为arrayList以及arraylist数组截取的简单方法 package xiaobai; import java.util.ArrayList; import java ...
- Java中数组转为List三种情况的优劣对比,常犯的类型转换错误原因解析
一.最常见方式(未必最佳)通过 Arrays.asList(strArray) 方式,将数组转换List后,不能对List增删,只能查改,否则抛异常. 关键代码:List list = Arrays. ...
- java中Executor、ExecutorService、ThreadPoolExecutor介绍
源码非常简单,只有一个execute(Runnable command)回调接口 public interface Executor { /** * Executes the given c ...
随机推荐
- Django-Oscar小记:如何使用高版本Django开发网页的SEO模块
在使用Google搜索Django的SEO插件时,很多插件都没有更新到Python3.x,有的插件更新到了Python的高版本,但是不适用于Django的2.x. Django在升级到版本2.x的时候 ...
- 2018-08-11 中文代码示例之Spring Boot 2.0.3问好
上次试用Spring Boot还是两年前: 中文代码示例之Spring Boot 1.3.3演示. 打算用在一个讨论组内小项目上, 于是从官网Building an Application with ...
- js替换字符中的斜杠反斜杠
var reg=/\\|\//g; var a="a\a\\a/b" alert(a.replace(reg,"-"));
- Ubuntu、deepin 安装 mysql
在 Ubuntu 和 deepin 安装 mysql 是很简单的,只需要几条简单的命令即可 1. sudo apt-get install mysql-server 2. sudo apt-get ...
- 自定义控件详解(六):Paint 画笔MaskFilter过滤
首先看一个API:setMaskFilter(MaskFilter maskfilter): 设置MaskFilter,可以用不同的MaskFilter实现滤镜的效果,如滤化,立体等. 以下有两个Ma ...
- ionic开发中,输入法键盘弹出遮挡住div元素
采用ionic 开发中,遇到键盘弹出遮挡元素的问题. 以登陆页面为例,输入用户名和密码时,键盘遮挡了登陆按钮. 最终采用自定义指令解决了问题: .directive('popupKeyBoardSho ...
- php get接口,并在浏览器中以json格式返回查找到的数据
php查询数据有6个步骤,分别为: 连接数据库服务器,使用的命令为:mysql_connect("服务器名称","用户名","密码") 选择 ...
- recovery 下界面UI旋转90 180 270修改
原文修改出自简书:https://www.jianshu.com/p/768fdd954061 应该是MTK修改的google源码,支持recovery下屏幕旋转90/180/270, 作者把MTK的 ...
- MySQL 约束、表连接、表关联、索引
一.外键: 1.什么是外键 2.外键语法 3.外键的条件 4.添加外键 5.删除外键 1.什么是外键: 主键:是唯一标识一条记录,不能有重复的,不允许为空,用来保证数据完整性. 外键:是另一表的唯一性 ...
- mysql----JOIN Quiz
JOIN quiz game id mdate stadium team1 team2 1001 8 June 2012 National Stadium, Warsaw POL GRE 1002 8 ...