【问题标题】:How to use the threads from a thread pool for every httprequest in java?java - 如何为java中的每个httprequest使用线程池中的线程?
【发布时间】:2011-12-01 07:34:33
【问题描述】:

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

提前致谢

代码是

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

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

【问题讨论】:

  • 是不是要为 httpClien 对象创建一个池?

标签: java multithreading httpclient


【解决方案1】:

您可以使用 Executors 并传递您自己的 Runnable 来处理您的 httpResponse。代码sn-p:

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));
}

【讨论】:

    【解决方案2】:

    您可能应该创建一个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。并将其标记为作业(闻起来像一个)

    【讨论】:

      猜你喜欢
      • 2016-05-15
      • 2019-08-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-19
      • 2018-07-24
      • 2011-08-10
      相关资源
      最近更新 更多