gpt4 book ai didi

java - 计时器的 run 方法中调用的方法返回一个我需要在上游使用的值

转载 作者:行者123 更新时间:2023-12-02 12:26:10 26 4
gpt4 key购买 nike

我有以下计时器代码,并且根据 run 方法的执行,无论成功与否,我想返回一个 boolean 值。

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

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

    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;
}

最佳答案

只需使用 Callable 代替 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 connected; 

将会

return countdown.get();

关于java - 计时器的 run 方法中调用的方法返回一个我需要在上游使用的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45484254/

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