gpt4 book ai didi

java - 多线程java优化

转载 作者:行者123 更新时间:2023-11-29 10:08:58 26 4
gpt4 key购买 nike

在我的程序中,我尝试掌握如何使用 ExecutorService 来优化我的程序。出于某种原因,它在两个网址上卡住了一点。 http://sjsu.edu/https://paypal.com .当它位于这两个上时,它不会继续执行其他 URLS。

即使这两个域的响应速度不够快,其他 3 个可用线程是否应该不继续?

如何以最好的方式解决这个问题?

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

String[] hostList = {"http://crunchify.com", "http://yahoo.com",
"http://www.ebay.com", "http://google.com",
"http://www.example.co", "https://paypal.com",
"http://bing.com/", "http://techcrunch.com/",
"http://mashable.com/", "http://thenextweb.com/",
"http://wordpress.com/", "http://cphbusiness.dk/",
"http://example.com/", "http://sjsu.edu/",
"http://ebay.co.uk/", "http://google.co.uk/",
"http://www.wikipedia.org/",
"http://dr.dk", "http://pol.dk", "https://www.google.dk",
"http://phoronix.com", "http://www.webupd8.org/",
"https://studypoint-plaul.rhcloud.com/", "http://stackoverflow.com",
"http://docs.oracle.com", "https://fronter.com",
"http://imgur.com/", "http://www.imagemagick.org"
};

List<CallableImpl> callList = new ArrayList();
ExecutorService es = Executors.newFixedThreadPool(4);

for (String url : hostList) {
CallableImpl callable = new CallableImpl(url);
callList.add(callable);
}
for (CallableImpl callableImpl : callList) {
System.out.println("Trying to connect to: " + callableImpl.getUrl());
Future<String> lol = es.submit(callableImpl);
System.out.println("status: " + lol.get());
}

es.shutdown();

}
}

我的可调用实现

public class CallableImpl implements Callable<String> {

private final String url;

public CallableImpl(String url) {
this.url = url;
}

public String getUrl() {
return url;
}

@Override
public String call() {
String result = "Error";

try {
URL siteURL = new URL(url);
HttpURLConnection connection = (HttpURLConnection) siteURL
.openConnection();
connection.setRequestMethod("GET");

connection.connect();

int code = connection.getResponseCode();
if (code == 200) {
result = "Green";
}

if (code == 301) {
result = "Redirect";
}

} catch (IOException e) {
result = "->Red<-";
}
return result;
}
}

最佳答案

在您的代码中,您将 Callable 一个一个地提交给 ExecutorService 并立即调用 Future.get() ,它将阻塞直到结果准备好(或在运行时抛出异常)。

你最好用 CompletionSerivce 包装 ExecutorService ,它会在结果准备好后立即提供结果。并将 for 循环分成两个循环:一个用于提交所有 Callable,第二个用于检查结果。

ExecutorService es = Executors.newFixedThreadPool(4);
ExecutorCompletionService<String> completionService = new ExecutorCompletionService<>(es);

for (CallableImpl callableImpl : callList) {
System.out.println("Trying to connect to: " + callableImpl.getUrl());
completionService.submit(callableImpl);
}
for (int i = 0; i < callList.size(); ++i) {
completionService.take().get(); //fetch next finished Future and check its result
}

关于java - 多线程java优化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51966983/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com