2016-10-28 34 views
2
import java.util.concurrent.ExecutionException; 
import java.util.concurrent.ExecutorService; 
import java.util.concurrent.Executors; 
import java.util.concurrent.Future; 

import javafx.concurrent.Task; 


public class T { 

    public static void main(String[] args) { 

     ExecutorService executorService = Executors.newSingleThreadExecutor(); 

     Task t = new Task(){ 

      @Override 
      protected Object call() throws Exception { 
       System.out.println(1/0); 
       return null; 
      } 

     }; 

     //My progresss Bar in JavaFX 
     //Progressbar.progressProperty().bind(t.progressProperty()); 

     Future future = executorService.submit(t); 

     try { 
      future.get(); 
     } catch (InterruptedException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } catch (ExecutionException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } //returns null if the task has finished correctly. 

     executorService.shutdown(); 


} 
} 

我有一個類似於這樣的代碼我的代碼任務在對象調用中有引發sql異常的內部方法調用,但我無法在Executor服務中捕獲它也在提交調用上方我有一個javafx進度條但也似乎像使用未來的主要用戶界面一樣陷入困境。沒有未來的進度條的作品。如何在java fx應用程序中捕獲任務異常?

回答

4

Future.get是一個阻塞呼叫。這就是UI掛起的原因。

請勿使用Future來獲得結果。而是使用TaskonSucceeded事件處理程序。 onFailed事件處理程序可用於獲取該異常。例如:

t.setOnSucceeded(evt -> System.out.println(t.getValue())); 
t.setOnFailed(evt -> { 
    System.err.println("The task failed with the following exception:"); 
    t.getException().printStackTrace(System.err); 
}); 
executorService.submit(t); 

順便說一句:兩個處理程序JavaFX應用程序線程上運行,因此可以安全地用於修改UI,以顯示結果/錯誤給用戶。

相關問題