java - 为什么这个 Future 的方法阻塞了主线程?

标签 java multithreading future

ExecutorService executor = Executors.newFixedThreadPool(2);

Future<Integer> calculate(Integer input) {
    return executor.submit(() -> {
        Thread.sleep(3000);
        return input * input;
    });
}

public static void main(String []args) throws Exception {
    Main m = new Main();
    System.out.println(m.calculate(5).get());
    System.out.println("Main");

我们使用 2 个线程向 Executor 提交 Callable,但是当我告诉 m.calculate(5).get()它阻塞了主线程。
所以,我不明白,何时以及为什么应该使用 Future如果它阻塞了主线程并且不异步运行?

最佳答案

如果您查看 Future::get 的文档它说:“如有必要,等待计算完成,然后检索其结果。”通过调用此方法,您同意在主线程中等待结果。

您可以通过调用 Future::isDone 检查 Future 是否已完成,它返回 boolean 值。

在您的场景中,它可以像这样使用

public static void main(String []args) throws Exception {
    Main m = new Main();
    Future<Integer> futureInt = m.calculate(5);
    // do some other asynchronous task or something in main thread while futureInt is doing its calculations
    // and then call Future::get
    int result = futureInt.get();

见:doc

关于java - 为什么这个 Future 的方法阻塞了主线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59892686/

相关文章:

java - Drools 中的正则表达式

java - 无法为用户设置PhotoUri/位置不存在对象

Java Web Start 导致执行缓慢

java - 自定义多线程 : limiting number of tasks of some type to be executed in parallel, 不限制其他类型任务

ruby - 我们可以在 Ruby 中并行运行多线程吗?

c++ - 为什么 future::wait() 不阻塞

Java 泛型类型不匹配

c++ - 不同步的多线程中的变量访问

scala - 并行运行两个scala函数,5分钟后返回最新值

multithreading - 为什么在返回 `Future::poll` 后没有重复调用 `NotReady` ?