【问题标题】:Why this Java program hangs (asynchronous html downloader)?为什么这个 Java 程序挂起(异步 html 下载器)?
【发布时间】:2015-02-28 08:33:18
【问题描述】:

您能告诉我为什么这个 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();
    }
}

【问题讨论】:

  • 挂起怎么办?它打印什么吗?

标签: java multithreading asynchronous


【解决方案1】:

Executors.newFixedThreadPool() 的 javadoc 说它返回一个 ExecutorService 的实例。 ExecutorService 的 javadoc 显示它有一个 shutdown() 方法。

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

就像你这样做

Object o = new Integer(34);

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

Integer o = new Integer(34);

那么你可以在 o 上使用 Integer 方法。

我不想粗鲁,但在考虑非常非常复杂的多线程编程之前,你应该掌握这些基本知识。

【讨论】:

  • 谢谢。将 Executor 替换为 ExecutorService 并添加了关闭功能。现在好了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-19
  • 1970-01-01
  • 2012-01-16
  • 2011-05-17
  • 2020-07-28
相关资源
最近更新 更多