在Java中,将ExecutorService转为守护程序
来源:互联网 发布:android 监听数据变化 编辑:程序博客网 时间:2024/06/02 07:01
问题描述
我正在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, thekeepAliveTime
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
类,即创建守护进程线程而不是常规线程。
参考文献
- Turning an ExecutorService to daemon in Java
注:本文内容整合自google/baidu/bing辅助翻译的英文资料结果。如果您对结果不满意,可以加入我们改善翻译效果:gxnotes#qq.com(#替换为@)。
- 在Java中,将ExecutorService转为守护程序
- 将java程序转为为exe可执行文件
- 在linux中开发守护程序
- java中ExecutorService接口
- java中ExecutorService接口
- Java程序将字符串转为unicode的方法
- 将自己的Java程序转为exe文件
- java中Executor、ExecutorService…
- java中Executor、ExecutorService、ThreadPoolExecutor
- java将InputStream转为String
- Java将图片转为base64
- java将unicode转为汉字
- Java中守护线程
- crontab方式在linux中守护java进程
- 在Android中使用ExecutorService、Executors、Feature
- java(SWING)守护程序
- 如何将C++程序转为Pascal语法
- 如何将C++程序转为Pascal语法
- 爱前端JS基础课程笔记1-20
- scp 跨机远程拷贝
- XUtils3导入Android Studio
- 3selenium+python 定位
- Python爬虫
- 在Java中,将ExecutorService转为守护程序
- GOS系列之下载附件
- C# Server.MapPath 未将对象引用设置到对象的实例
- 第七届蓝桥杯B组省赛--方块分割
- P1020 导弹拦截
- sprinv mvc+hibernate4 事物配置管理
- SpringMVC开发所遇问题总结
- 联币网:建立区块链大生态系统 分享数字货币红利
- 学习反馈-02 ajax, svn, jquery easyui概念