CWIKIUS

Java 中如何限制方法的返回时间

2023-02-10  本文已影响0人  HoneyMoose

最近在研究 ChatGPT 的 API 调用。

因为 ChatGPT 的 API 调用时间通常超过 30 秒。

所以我们希望在程序中限制这个方法的执行时间,不要让方法花太长时间去执行了。

JDK 方法

可以使用 JDK 中的 ExecutorService 方法来对调用的方法进行处理。

代码如下:

ExecutorServiceexecutor =newCachedThreadPool();Callable task =newCallable() {publicStringcall() {returncallChatGPT(content);            }        };Future future = executor.submit(task);try{Objectresult = future.get(15,TimeUnit.SECONDS);            contentGPT = (String) result;        }catch(TimeoutExceptionex) {            contentGPT ="ChatGPT API Time out, Please Re-try it";        }catch(InterruptedExceptione) {            contentGPT ="ChatGPT API Time out, Please Re-try it";        }catch(ExecutionExceptione) {            contentGPT ="ChatGPT API Time out, Please Re-try it";        }finally{            future.cancel(true);// may or may not desire this}

在我们的调用方法 callChatGPT 中,我们配置了一个 ExecutorService 执行器。

在这个执行器中,我们配置一个任务。

然后这个任务我们指定了执行时间为 15 秒。

如果这个方法的执行时间超过了 15 秒,程序将会抛出一个异常。

可以通过这个方法来限制方法的执行时间。

https://www.ossez.com/t/java/14322

上一篇下一篇

猜你喜欢

热点阅读