我有一个函数可以给我一个服务状态:
public ServiceState getServiceState(){
return someService().getState(); //currently state return "NOTACTIVE"
}
当我在系统上调用某个方法时,服务应该在 x 时间后(未知时间)处于 Activity 状态:
someService().startService(); //after a while, the state of the service should be active
如果我只想检查一次服务状态,我会这样做:
public boolean checkCurrentState(String modeToCheck){
return getServiceState() == modeToCheck;
}
checkCurrentState("ACTIVE"); //return true or false depends on the state
问题是,状态需要一些时间来改变,所以我需要以下内容:
我需要检查当前状态(在我定义的 x 秒的 while 循环中),如果 x 秒后服务仍处于“NOTACTIVE”模式,我将抛出某种异常来终止我的程序.
于是想到了以下解决方案: 一个有 2 个变量的方法:一个变量表示可以在方法内部调用的通用函数,一个变量是我允许它继续检查的时间:(伪代码)
public void runGenericForXSeconds(Func function,int seconds) throws SOMEEXCEPTION{
int timeout = currentTime + seconds; //milliseconds
while (currentTime < timeout){
if (function.invoke()) return; //if true exits the method, for the rest of the program, we are all good
}
throw new SOMEEXCEPTION("something failed"); //the function failed
}
类似的东西,但我需要它尽可能通用(调用的方法部分应该采用其他方法),Java 8 lambda 是解决方案的一部分吗?
最佳答案
具体使用您的示例:
public void runGenericForXSeconds(BooleanSupplier supplier, int seconds) throws SOMEEXCEPTION {
int timeout = currentTime + seconds; // milliseconds
while (currentTime < timeout) {
if (supplier.getAsBoolean())
return; // if true exits the method, for the rest of the program, we are all good
}
throw new SOMEEXCEPTION("something failed"); // the function failed
}
然后您的供应商只需要返回true
或false
。例如:
runGenericForXSeconds(() -> !checkCurrentState("ACTIVE"), 100);
请注意,您有一个繁忙的循环。除非您明确想要这样做,否则您可能希望使用 Thread.sleep()
或类似方法在调用之间暂停。
关于java - 如何使用 java 8 在超时的情况下调用另一个函数内的通用函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55228398/