gpt4 book ai didi

java - future 任务不起作用

转载 作者:行者123 更新时间:2023-11-29 07:00:30 24 4
gpt4 key购买 nike

我以类似于 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 中运行 FutureTaskstart() 方法是在尝试获取结果之前调用。

关于java - future 任务不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26896316/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com