我正在使用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
发布评论