在给定时间内未提交任何任务时,关闭ExecutorService

编程入门 行业动态 更新时间:2024-10-14 00:29:24
本文介绍了在给定时间内未提交任何任务时,关闭ExecutorService的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在使用ExecutorService调用服务,该服务基本上连接到应用程序(通过SSH本地或远程),并允许向其发送命令并获取其输出.

I'm using an ExecutorService to call a service which basically connects to an application (local or remote via SSH), and allows to send commands to it and get its output.

因此,由ExecutorService创建的Thread正在等待用户输入,然后通过调用方法的实现将该输入作为任务处理,该方法返回输出,如下所示:

So, the Thread created by the ExecutorService is waiting for user input, and this input is then processed as a task through an implementation of the call method, which returns the output and looks like this:

@Override public String call() throws Exception { write(command); return readResult(); }

我想在给定时间内没有调用任何任务的情况下停止Thread(关闭ExecutorService),但是我找不到如何执行的操作... Future.get或ExecutorService.invoke[All|Any]可以处理超时,但只能处理它所调用的任务.

I would like to stop the Thread (shutdown the ExecutorService) when no task has been called for a given time, but I can't find how to do it... Future.get or ExecutorService.invoke[All|Any] can handle a timeout, but only regarding tasks it calls.

关于我如何能够做到这一点的任何想法?

Any idea on how I could manage to do this?

提前谢谢!

此致

Zim

推荐答案

您可以使用Executors.newCachedThreadPool(),其文档显示:

You could just use Executors.newCachedThreadPool(), whose doc says:

六十秒未使用的线程被终止,并从高速缓存中删除.因此,保持空闲时间足够长的池不会消耗任何资源.请注意,可以使用ThreadPoolExecutor构造函数创建具有相似属性但不同详细信息(例如超时参数)的池.

Threads that have not been used for sixty seconds are terminated and removed from the cache. Thus, a pool that remains idle for long enough will not consume any resources. Note that pools with similar properties but different details (for example, timeout parameters) may be created using ThreadPoolExecutor constructors.

这将关闭线程,而不是整个执行器,但是如果执行器实际上没有占用任何资源,那应该没问题.

This shuts down the threads, not the entire executor, but that should be fine if the executor isn't actually taking any resources.

更多推荐

在给定时间内未提交任何任务时,关闭ExecutorService

本文发布于:2023-11-27 13:31:04,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1638278.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:内未   时间   ExecutorService

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!