gpt4 book ai didi

java - FutureTask 如何管理线程..?

转载 作者:行者123 更新时间:2023-12-01 15:02:17 27 4
gpt4 key购买 nike

我正在尝试将请求发送到服务器...直到请求没有响应我想执行一个打印整数的循环..问题是我的循环一直持续下去,如果我执行它直到 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);
}

关于java - FutureTask 如何管理线程..?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13467983/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com