如何在java中为每个http请求使用线程池中的线程?

时间:2011-12-01 07:34:33

标签: java multithreading httpclient

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

提前致谢

代码是

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

这里我需要为每个httpresponse

使用线程池中的线程

2 个答案:

答案 0 :(得分:1)

你应该创建一个FixedThreadExecutor http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/Executors.html#newFixedThreadPool(int

然后创建Runnable个任务 http://docs.oracle.com/javase/7/docs/api/java/lang/Runnable.html

并通过sumbit()executeAll()函数在执行程序中运行它们 http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ExecutorService.html

也许你也应该在线程中做HttPRequest。并将其标记为作业(它闻起来像一个)

答案 1 :(得分:0)

您可以使用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));
}