簡體   English   中英

FutureTask如何管理線程..?

[英]FutureTask how to manage threads..?

我正在嘗試將請求發送到服務器...並且直到請求未響應我都想執行循環打印整數..問題是我的循環不斷,如果我執行到100,它將打印100個值,如果直到1000它打印1000。我想要的是循環應取決於響應。 響應一發生,就應該停止循環線程...

  public class ServiceInteraction {
  FutureTask<JSONArray> task;
  public JSONArray addUser(List<BasicNameValuePair> postPairs_interaction){
    JSONArray jArray;
    task = new FutureTask<JSONArray>(new Service_C(postPairs_interaction));
    ExecutorService pool = Executors.newFixedThreadPool(2);
    pool.submit(task);
    for(int i = 0 ; i < 1000; i++){
        System.out.println("value is "+i);
    }//End of for loop
    try{
        return (jArray = task.get());
    }catch(InterruptedException e){
        return null;
    }catch(ExecutionException e){
        return null;
    }
  }//End Of addUser

這是我的service_c類代碼...

public Service_C(List<BasicNameValuePair> postPairs) {
    this.postPairs = postPairs;
}

@Override
public JSONArray call() throws Exception {
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost post = new      HttpPost("http://10.0.0.62:8080/IDocWS/"+postPairs.get(0).getValue());
    post.setEntity(new UrlEncodedFormEntity(postPairs));
    ResponseHandler respHandler = new BasicResponseHandler();
    String responseData = (String) httpclient.execute(post,respHandler);

    try {
        JSONArray jArray;
        jArray = new JSONArray(responseData);
        return jArray;

    } catch (JSONException ex) {
        Logger.getLogger(Service.class.getName()).log(Level.SEVERE, null, ex);
        System.out.println("Error in getting response from the user");
        return null;
    }
}//End of call method

您可以嘗試以下方法:

 for (int i = 0;;i++){
        if (task.isDone()) {
              break;
        }
        System.out.println("value is "+i);
 }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM