为什么这个 Future 的方法会阻塞主线程?

Rar*_*y7- 1 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");
Run Code Online (Sandbox Code Playgroud)

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

Pio*_*ski 7

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

您可以通过调用Future::isDone返回布尔值的来检查 Future 是否已完成。

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

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();
Run Code Online (Sandbox Code Playgroud)

见:文档

  • 这意味着 Future 只是任务结果的占位符,在您调用 Future::get 时可能存在也可能不存在。 (4认同)

Mar*_*nik 5

Future确实是一个非常有限的抽象,在更现实的情况下,您应该使用它CompletableFutureFuture是一个相当古老的类(我猜是从java 1.5开始)所以业界对并发编程领域的理解逐渐发展,

尽管如此,它本身仍然很有用。

如果不是生成一个 future 并立即调用get它,我们希望生成许多任务并将结果存储在某个列表中,该怎么办:

List<Future<Integer>> futures = new ArrayList<>(10);
for(int i = 0 ; i< 10; i++) {
   futures.add(calculate(<some_integer>));
}
// at this point all futures are running concurrently
for(int i = 0 ; i < 10; i++) {
   futures.get(i).get(); // will either return immediately or we'll block the main thread but the point is that all the calculations will run concurrently
}
Run Code Online (Sandbox Code Playgroud)