为什么这个 Java 程序挂起(异步 html 下载程序)?

Why this Java program hangs (asynchronous html downloader)?

你能告诉我这个 Java 程序挂起的原因吗? 这是一个使用 ExecutorCompletionService 异步下载 HTML 的简单程序。我尝试使用 executor.shutdown()completionService.shutdown(),但都给出了 no such method。我认为问题出在 executorcompletionService 但无法弄清楚如何阻止他们不使用他们的关闭方法。

import java.io.BufferedReader;
import java.io.InputStreamReader;

import java.net.URL;
import java.util.concurrent.*;

class Main {

    public static void main(String[] args) throws Exception {

        Executor executor = Executors.newFixedThreadPool(2);
        CompletionService<String> completionService = new ExecutorCompletionService<>(executor);
        completionService.submit(new GetPageTask(new URL("http://xn--80adxoelo.xn--p1ai/")));//slow web site
        completionService.submit(new GetPageTask(new URL("http://example.com")));

        Future<String> future = completionService.take();
        System.out.println(future.get());

        Future<String> future2 = completionService.take();
        System.out.println(future2.get());


    }
}

final class GetPageTask implements Callable<String> {
    private final URL url;

    GetPageTask(URL url) {
        this.url = url;
    }

    private String getPage() throws Exception {
        final BufferedReader reader = new BufferedReader(new InputStreamReader(this.url.openStream()));
        String str = "";
        String line;
        while ((line = reader.readLine()) != null) {
            str += line + "\n";
        }
        reader.close();
        return str;
    }

    @Override
    public String call() throws Exception {
        return getPage();
    }
}

Executors.newFixedThreadPool() says that it returns an instance of ExecutorService. The javadoc of ExecutorService 的 javadoc 表明它有一个 shutdown() 方法。

您无法访问它,因为您选择将变量声明为 Executor 而不是 ExecutorService

就像你这样做一样

Object o = new Integer(34);

您将无法在 o 上调用任何 Integer 方法。而如果你这样做

Integer o = new Integer(34);

然后你可以在 o 上使用 Integer 方法。

我不想无礼,但这是您在考虑多线程编程之前应该掌握的非常基本的东西,多线程编程非常非常复杂。