在某些代码块运行时间超过可接受的时间后,是否可以强制 Java 抛出异常?
原文由 htf 发布,翻译遵循 CC BY-SA 4.0 许可协议
在某些代码块运行时间超过可接受的时间后,是否可以强制 Java 抛出异常?
原文由 htf 发布,翻译遵循 CC BY-SA 4.0 许可协议
这是我知道的最简单的方法:
final Runnable stuffToDo = new Thread() {
@Override
public void run() {
/* Do stuff here. */
}
};
final ExecutorService executor = Executors.newSingleThreadExecutor();
final Future future = executor.submit(stuffToDo);
executor.shutdown(); // This does not cancel the already-scheduled task.
try {
future.get(5, TimeUnit.MINUTES);
}
catch (InterruptedException ie) {
/* Handle the interruption. Or ignore it. */
}
catch (ExecutionException ee) {
/* Handle the error. Or ignore it. */
}
catch (TimeoutException te) {
/* Handle the timeout. Or ignore it. */
}
if (!executor.isTerminated())
executor.shutdownNow(); // If you want to stop the code that hasn't finished.
或者,您可以创建一个 TimeLimitedCodeBlock 类来包装此功能,然后您可以在任何需要的地方使用它,如下所示:
new TimeLimitedCodeBlock(5, TimeUnit.MINUTES) { @Override public void codeBlock() {
// Do stuff here.
}}.run();
原文由 user2116890 发布,翻译遵循 CC BY-SA 3.0 许可协议
15 回答8.2k 阅读
8 回答5.9k 阅读
1 回答4.1k 阅读✓ 已解决
3 回答2.2k 阅读✓ 已解决
2 回答3.1k 阅读
2 回答3.8k 阅读
1 回答2.2k 阅读✓ 已解决
是的,但是强制另一个线程中断随机代码行通常是一个非常糟糕的主意。如果您打算关闭该过程,您只会这样做。
您可以做的是在一定时间后使用
Thread.interrupt()
执行任务。但是,除非代码对此进行检查,否则它将无法工作。 ExecutorService 可以使用Future.cancel(true)
使这更容易最好让代码自己计时并在需要时停止。