我有两个线程使用HTTPClientTest的相同实例。两个线程在同一HTTPClientTest上调用send方法。我应该如何为调用send方法的每个线程设置不同的套接字超时。如果我在send方法中做这样的事情,那么两个执行send方法的线程将具有相同的套接字超时。
managerParams.setSoTimeout(60); connectionManager.setParams(managerParams);
如何为在同一HTTPClientTest实例上执行send方法的多个线程创建不同的套接字超时。
public class HTTPClientTest implements Runnable{
private HttpClient httpClient;
private MultiThreadedHttpConnectionManager connectionManager;
private HttpConnectionManagerParams managerParams;
private HttpClientTest()
{
connectionManager = new MultiThreadedHttpConnectionManager();
httpClient = new HttpClient(connectionManager);
}
public static synchronized HTTPClientTest getInstance()
{
if(instance == null)
instance = new HTTPClientTest();
return instance;
}
public void send(String message, String url)
{
PostMethod post = new PostMethod(url);
String reply = "";
String length = message.length() + "";
post.setRequestHeader("Content-Length", length);
try
{
System.out.println("HTTP request: " + message);
StringRequestEntity postBody = new StringRequestEntity(message, "text/xml", "UTF-8");
post.setRequestEntity(postBody);
int status = httpClient.executeMethod(post);
System.out.println("HTTP status: " + status);
reply = post.getResponseBodyAsString();
System.out.println("HTTP Post response code: " + reply);
}
catch(HttpException e)
{
e.printStackTrace();
}
catch(IOException e)
{
e.printStackTrace();
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
post.releaseConnection();
}
}
}
最佳答案
这很容易:
get.getParams().setParameter("http.socket.timeout",20000);
httpclient.execute(get);
方法不是由线程共享的,是吗?
根据需要进行修改。