FX Task,返回一个值总是返回null [英] FX Task, returning a value always returns null
问题描述
我正在尝试从FX任务返回一个字符串。
I am trying to return a String from a FX Task.
预期输出:true,testABC。
Expected output: true,testABC.
实际输出:true,null。
Real output: 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;
}}
推荐答案
任务
实现 Runnable
,但不是 Callable
。所以当你调用 pool.submit(myTask)
时,你正在调用重载形式的 ExecutorService.submit(...)
获取 Runnable
。当然,一般来说, Runnable
s不会返回值,因此从该版本的<返回 Future
code>提交(...),正如Aerus已经指出的那样,只需从返回
方法(它无法从 null
get() Runnable
获取值)。
Task
implements Runnable
, but not Callable
. So when you call pool.submit(myTask)
, you are calling the overloaded form of ExecutorService.submit(...)
taking a Runnable
. In general, of course, Runnable
s do not return values, so the Future
that is returned from that version of submit(...)
, as Aerus has already pointed out, just returns null
from its get()
method (it cannot get a value from the Runnable
).
然而,任务
也直接扩展 FutureTask
,所以您可以直接使用您的任务来获得结果。只需
However, Task
also extends FutureTask
directly, so you can use your task directly to get the result. Just do
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);
}
这篇关于FX Task,返回一个值总是返回null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!