gpt4 book ai didi

java - 如何为 java 中的每个 httprequest 使用线程池中的线程?

转载 作者:行者123 更新时间:2023-11-30 09:43:21 25 4
gpt4 key购买 nike

我需要创建一个固定大小的线程池,并为每个 http 请求使用该线程。任何人都可以指定如何执行此操作吗?

提前致谢

代码是

    HttpGet httpGet = new HttpGet(url);
HttpClient httpClient = new DefaultHttpClient();
HttpResponse httpResponse = httpClient.execute(httpGet);
return httpResponse;

这里我需要为每个 httpresponse 使用线程池中的线程

最佳答案

您可以使用 Executors 并传递您自己的 Runnable,它将处理您的 httpResponse。代码片段:

public class MyHttpResponseHandler implements Runnable {

private HttpResponse httpResponse = null;

public MyHttpResponseHandler(HttpResponse httpResponse){
this.httpResponse = httpResponse;
}
@Override
public void run() {
//Do something with the httpResponse
}
}

void processHttpResponse(){
HttpGet httpGet = new HttpGet(url);
HttpClient httpClient = new DefaultHttpClient();
HttpResponse httpResponse = httpClient.execute(httpGet);
ExecutorService executor = Executors.newFixedThreadPool(10);
executor.execute(new MyHttpResponseHandler(httpResponse));
}

关于java - 如何为 java 中的每个 httprequest 使用线程池中的线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8337909/

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