Java:在某个代码块上设置超时?

新手上路,请多包涵

在某些代码块运行时间超过可接受的时间后,是否可以强制 Java 抛出异常?

原文由 htf 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 637
2 个回答

是的,但是强制另一个线程中断随机代码行通常是一个非常糟糕的主意。如果您打算关闭该过程,您只会这样做。

您可以做的是在一定时间后使用 Thread.interrupt() 执行任务。但是,除非代码对此进行检查,否则它将无法工作。 ExecutorService 可以使用 Future.cancel(true) 使这更容易

最好让代码自己计时并在需要时停止。

原文由 Peter Lawrey 发布,翻译遵循 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 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题