2015-03-13 85 views
0

我有一個要執行的Task,並且提交給緩存線程池ExecutorService。它運行平穩,但我需要能夠檢索其可回收價值。這怎麼能做到?JavaFX:使用執行程序在線程池中運行時任務的可返回值

樣品的編號:

ExecutorService threadPool = Executors.newCachedThreadPool(runnableTask -> { 
    Thread thread = new Thread(runnableTask); 
    thread.setDaemon(true); 
    return thread; 
}); 
Button btn = new Button("Run Task"); 
btn.setOnAction(actionEvent -> { 
    try { 
     Object get = threadPool.submit(new Task<String>() { 
      @Override 
      protected String call() throws Exception { 
       //simulating long-running task 
        Thread.sleep(3_000); 
       //return result 
        return "Warren Nocos"; 
      } 
     }).get(); 
     System.out.println(get); 
    } catch (InterruptedException | ExecutionException ex) { 
     logger.log(Level.SEVERE, ex.getMessage(), ex); 
    } 
}); 

的輸出是零。

回答

2

使用onSucceeded()回調(這將在JavaFX應用程序線程中執行):

Button btn = new Button("Run Task"); 
btn.setOnAction(actionEvent -> { 
    Task<String> task = new Task<String>() { 
     @Override 
     protected String call() throws Exception { 
      //simulating long-running task 
       Thread.sleep(3_000); 
      //return result 
       return "Warren Nocos"; 
     } 
    }; 
    task.setOnSucceeded(event -> { 
     String result = task.getValue(); 
     System.out.println(result); 
    }); 
    task.setOnFailed(event -> { 
     task.getException().printStackTrace(); 
    }); 
    threadPool.execute(task); 
}); 
相關問題