2017-08-03 129 views
0

我有下面的定時器代碼,並且根據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; 
} 

回答

0

您需要安排可贖回,而不是一個Runnable做到這一點。

這會做你想要什麼:

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

return countdown.get(); 

注意,此方法將阻塞,直到預定的調用已完成。

1

只要使用可調用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(); 
+0

你能編輯代碼嗎? – Harriet

相關問題