我正在尝试从 FX 任务返回字符串。
预期输出:true,testABC。
实际输出:true,null。
任务调用:
public static void main(String[] args) {
ExecutorService pool = Executors.newCachedThreadPool();
Future<String> my_String = (Future<String>) pool.submit(new my_task());
try {
Thread.sleep(500);
System.out.println(my_String.isDone());
System.out.println(my_String.get());//gettings the String from the future
} catch (InterruptedException | ExecutionException ex) {
Logger.getLogger(Return_test.class.getName()).log(Level.SEVERE, null, ex);
}}
任务:
public class my_task extends Task<String>{
@Override
protected String call() throws Exception {
String tempString = "testABC";
return tempString;
}}
最佳答案
Task
实现Runnable
,但不实现Callable
。因此,当您调用pool.submit(myTask)
时,您正在调用 overloaded form of ExecutorService.submit(...)
taking a Runnable
。当然,一般来说,Runnable
不会返回值,因此从该版本的 submit(...)
返回的 Future
正如 Aerus 已经指出的那样,仅从其 get()
方法返回 null
(它无法从 Runnable
获取值)。
但是,Task
也直接扩展了FutureTask
,因此您可以直接使用您的任务来获取结果。就这么做
Task<String> myTask = new my_task(); // Please use standard naming conventions, i.e. new MyTask();
pool.submit(myTask);
try {
// sleep is unnecessary, get() will block until ready anyway
System.out.println(myTask.get());
} catch (InterruptedException | ExecutionException ex) {
Logger.getLogger(Return_test.class.getName()).log(Level.SEVERE, null, ex);
}
关于java - FX Task,返回值总是返回null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29985455/