簡體   English   中英

為什么這個 Future 的方法會阻塞主線程?

[英]Why this Future's method is blocking main thread?

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 個線程將 Callable 提交給 Executor,但是當我告訴m.calculate(5).get()它阻塞主線程。 所以,我不明白,如果Future阻塞主線程並且不異步運行,我什么時候以及為什么應該使用它?

如果您查看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();

見: 文檔

Future確實是一個非常有限的抽象,在更現實的情況下,您應該使用CompletableFuture代替。 Future是一個相當古老的類(我猜從 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
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM