2011-12-01 125 views
2

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

在此先感谢

的代码是

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

在这里,我需要使用从线程池中的线程,每HttpResponse对象

+0

这是否意味着您要为httpClien对象创建池? – Sap

回答

0

你可以用遗嘱执行人,并通过自己的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)); 
} 
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

也许你houdl也在线程中执行HttPRequest。并将其标记为家庭作业(它闻起来像是一个)