gpt4 book ai didi

java - 如何防止此 Java 代码挂起

转载 作者:行者123 更新时间:2023-12-01 15:16:07 24 4
gpt4 key购买 nike

我有一个代理列表来测试它们是否是HTTP或Socks代理,但是下面的Java代码在调用connection.getContent()或connection.getInputStream()时挂起。我观察到,当代理服务器无法响应并且代码阻塞等待服务器响应时,就会出现此问题,如何防止此代码在服务器无法响应时永远挂起/阻塞,以便可以检查下一个代理。

import java.io.*;
import java.net.*;
import java.util.*;

public class ProxyTest {

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

InetSocketAddress proxyAddress = new InetSocketAddress("myproxyaddress", 1234);

Proxy.Type proxyType = detectProxyType(proxyAddress);
}

public static Proxy.Type detectProxyType(InetSocketAddress proxyAddress) throws IOException {

URL url = new URL("http://www.google.com/");

List<Proxy.Type> proxyTypesToTry = Arrays.asList(Proxy.Type.SOCKS, Proxy.Type.HTTP);

for(Proxy.Type proxyType : proxyTypesToTry) {

Proxy proxy = new Proxy(proxyType, proxyAddress);

URLConnection connection = null;

try {

connection = url.openConnection(proxy);

connection.setConnectTimeout(10000);
connection.setReadTimeout(10000);

connection.getContent();
//connection.getInputStream();

return(proxyType);
}

catch (SocketException e) {

e.printStackTrace();
}
}

return(null);
}
}

最佳答案

要并行执行操作,请使用线程。

for(Foo f : foos){
Thread t = new Thread(new Runnable(){
@Override
public void run(){
// blocking call
}
});
t.start();
}

更好的是,利用 java.util.concurrent 中的数据结构之一包。

关于java - 如何防止此 Java 代码挂起,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11586127/

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