gpt4 book ai didi

java - 如果程序在 n 秒后没有返回任何内容,如何在 java 中调用函数

转载 作者:行者123 更新时间:2023-11-30 07:46:44 26 4
gpt4 key购买 nike

我有这样一个函数:

public boolean doLogin() {
try {
somemethodForLogin();
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}

在这种情况下,如果 somemethodForLogin() 花费的时间比预期的多,比如 8 秒,我想返回 false 或抛出异常。我怎样才能做到这一点?

我在 somemethodForLogin() 之前添加了这样的内容:

new java.util.Timer().schedule(
new java.util.TimerTask() {
@Override
public void run() {
System.out.println("Returning after 8 seconds wait");
}
}, 8000);

但它总是会出现这种情况,即使调用成功也是如此。

最佳答案

您可以使用可完成的 future 来调用登录,然后在超时的情况下检索结果:

try {
CompletableFuture.runAsync(() -> somemethodForLogin())
.get(8, TimeUnit.SECONDS);
return true;
}catch(TimeoutException timeoutException) {
//Timeout handline here
return false; //or call other function
}

上面的 lambda 是一个 Supplier而不是 Runnable .

CompletableFuture 的 get方法记录如下:

Waits if necessary for at most the given time for this future to complete, and then returns its result, if available.
TimeoutException - if the wait timed out

编辑:
以上是使用 CompletableFuture<Void>因为电话正在接Runnable .如果somemethodForLogin()返回一个值,您可以使用相同的 API,但调用 supplyAsync :

Object loginResult = CompletableFuture.supplyAsync(() -> somemethodForLogin())
.get(8, TimeUnit.SECONDS);
//Just change the return types accordingly.

关于java - 如果程序在 n 秒后没有返回任何内容,如何在 java 中调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50501705/

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