在Java中指定的时间限制后杀死线程 [英] Killing thread after some specified time limit in Java

查看:90
本文介绍了在Java中指定的时间限制后杀死线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法在Java中指定的时间限制后终止子线程?
编辑:此特定线程也可能在最坏的情况下被阻塞(线程用于等待文件修改并阻塞直到发生此事件),所以我不确定interrupt()是否会成功?

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 执行 Runnable ,签出可以指定超时的方法。例如,

Make use of ExecutorService to execute the Runnable, 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();

这里任务当然实现 Runnable

这篇关于在Java中指定的时间限制后杀死线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆