方法调用 运行 定时器的方法 returns 我需要在上游使用的值

Method called in run method of a timer returns a value I need to use upstream

我有下面的定时器代码,根据运行方法的执行,是否成功,我想return一个boolean。

但是我收到错误消息: 在封闭范围内定义的局部变量 connected 必须是最终的或实际上是最终的。

我该如何解决这个问题来完成我想要的? 这是代码:

    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 的可调用实例:

<V> ScheduledFuture<V>  schedule​(Callable<V> callable, long delay, TimeUnit unit)  
Creates and executes a ScheduledFuture that becomes enabled after the given delay.

主要区别在于,Callable 可以 return 值(直接通过调用 return 语句)。

然后代替

return connected; 

将会

return countdown.get();

您需要安排 Callable 而不是 Runnable 来执行此操作。

这会做你想做的事:

ScheduledFuture<Boolean> countdown = scheduler.schedule(new Callable<Boolean>() {
    public Boolean call() {
        return attemptRetrieval(...);
    }}, 1, TimeUnit.MINUTES);

return countdown.get();

请注意,此方法将阻塞,直到计划调用完成。