我有一个这样的函数:
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/