gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 20:23:29 25 4
gpt4 key购买 nike

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

最佳答案

这是我所知道的最简单的方法:

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();

关于Java:在某个代码块上设置超时?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5715235/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com