在run方法中调用一个定时器的方法返回一个值我需要用上游
问题描述:
我有下面的定时器代码,并且根据run方法的执行情况判断它是否成功,我想返回一个布尔值。在run方法中调用一个定时器的方法返回一个值我需要用上游
但是,我收到错误消息: 在封闭范围内定义的局部变量必须是最终的或有效的最终结果。
如何解决此问题以实现我想要的功能? 下面是代码:
private boolean getSwitchesOnRc(NamedPipeClient pipe, DV_RC_EntryPoint rc_EntryPoint, int allowedAttempts, int counter){
final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
boolean connected = false;
ScheduledFuture<?> countdown = scheduler.schedule(new Runnable() {
@Override
public void run() {
connected = attemptRetrievalOfSwitches(pipe, rc_EntryPoint, allowedAttempts, counter);
}}, 1, TimeUnit.MINUTES);
return connected;
}
答
您需要安排可赎回,而不是一个Runnable做到这一点。
这会做你想要什么:
ScheduledFuture<Boolean> countdown = scheduler.schedule(new Callable<Boolean>() {
public Boolean call() {
return attemptRetrieval(...);
}}, 1, TimeUnit.MINUTES);
return countdown.get();
注意,此方法将阻塞,直到预定的调用已完成。
答
只要使用可调用insted的可运行的:
<V> ScheduledFuture<V> schedule(Callable<V> callable, long delay, TimeUnit unit)
Creates and executes a ScheduledFuture that becomes enabled after the given delay.
主要区别是,可赎回可(直接通过调用return语句)的返回值。
然后代替
return connected;
将
return countdown.get();
你能编辑代码吗? – Harriet