【发布时间】:2015-02-28 08:33:18
【问题描述】:
您能告诉我为什么这个 Java 程序会挂起吗?
这是一个使用 ExecutorCompletionService 异步下载 HTML 的简单程序。我尝试使用executor.shutdown() 和completionService.shutdown(),但都给no such method。我认为问题出在executor 和completionService 上,但不知道如何阻止他们不使用关闭方法。
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