简体   繁体   中英

FutureTask how to manage threads..?

I am trying to send reqeuest to server...and until request is not responded i want to execute a loop printing integers..problem is my loop goes on and on, if i execute it till 100 it prints 100 values and if till 1000 it prints 1000. What i want is that the looping should be depended upon the response. as soon as response occurs the loop thread should be stoped...

  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

Here is my service_c class code...

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

You can try this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM