java - future 任务不起作用

标签 java multithreading concurrency

我以类似于 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/

相关文章:

java - 如何在 libgdx 中正确实现声音切换?

java - 关于数据库更新的问题

java - 如何允许 Sprite 只从一侧移动到另一侧?

python - python 2中的Lock对象是否超时?

java - 为什么当队列溢出且所有线程都忙时拒绝处理程序不调用

java - 传递给另一个类时缺少值 - Android - Java?

c# - 如何在不挂起应用程序和减少 C# 时间的情况下使用 1M 记录执行 PROC

multithreading - 使用 GPU 进行并行 for 循环的最简单方法

java - 在同步块(synchronized block)内使用 wait()

java - Guava MapMaker和JDK ConcurrentMap是否使用读/写锁?