我以类似于 Brian Goetz 的书 Java Concurrency in Practice 中介绍的方式创建了一个 FutureTask
(代码示例可以在 here 中找到,列表 5.12)。
问题是即使给定 10 秒任务也会超时。该任务仅返回 true
,因此不应该有它发生的原因:
public static void main(String[] args) throws Exception {
FutureTask<Boolean> task = new FutureTask<>(new Callable<Boolean>() {
@Override
public Boolean call() throws Exception {
return true;
}
});
System.out.println(task.get(10, TimeUnit.SECONDS));
}
此代码打印:
Exception in thread "main" java.util.concurrent.TimeoutException
at java.util.concurrent.FutureTask.get(Unknown Source)
at Main.main(Main.java:19)
最佳答案
您还没有执行任务。永远不会有可用的结果。 javadoc州
This class provides a base implementation of
Future
, with methods to start and cancel a computation, query to see if the computation is complete, and retrieve the result of the computation. The result can only be retrieved when the computation has completed
将任务提交给 ExecutorService
以异步运行。
Executors.newSingleThreadExecutor().submit(task); // ideally shutdown the ExecutorService afterwards
或者同步运行
task.run();
在您提供的链接中,我假设在新的 Thread
中运行 FutureTask
的 start()
方法是在尝试获取结果之前调用。
关于java - future 任务不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26896316/