在 Java 中的某个指定时间限制后杀死线程 [英] Killing thread after some specified time limit in Java
本文介绍了在 Java 中的某个指定时间限制后杀死线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有没有办法在 Java 中的某个指定时间限制后杀死子线程?这个特定的线程也可能在最坏的情况下被阻塞(线程用于等待文件修改并阻塞直到发生此事件),所以我不确定中断()会成功吗?
Is there a way to kill a child thread after some specified time limit in Java? Also this particular thread may be blocked in its worst case (Thread is used to wait for a file modification and blocks until this event occurs), so im not sure that interrupt() will be successful?
推荐答案
利用 ExecutorService
来执行Callable
,检查可以指定超时的方法.例如
Make use of ExecutorService
to execute the Callable
, checkout the methods wherein you can specify the timeout. E.g.
ExecutorService executor = Executors.newSingleThreadExecutor();
executor.invokeAll(Arrays.asList(new Task()), 10, TimeUnit.MINUTES); // Timeout of 10 minutes.
executor.shutdown();
这里Task
当然实现了Callable
.
这篇关于在 Java 中的某个指定时间限制后杀死线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文