我有一个自定义服务模块,我在其中传递一个包含ID数组的JSON主体。我必须遍历这些ID并使用每个ID进行单独的Web服务调用以获取响应主体,然后将这些响应聚合到自定义JSON结构中。我有所有工作,但我想实现线程(或其某种方式)异步进行HTTP调用,而不是连续。我将如何在以下代码中实现线程:
ids = (JSONArray) jsonIn.get("IDs");
MyClass myClass = null;
List<MyClass> myClassList = new ArrayList<MyClass>();
for (int i = 0; i < ids.size(); i++) {
JSONObject p = (JSONObject)ids.get(i);
id = p.get("ID").toString();
//The HttpUrlConnection call is made in the getResponse() method
Gson gson = new Gson();
MyClassResponse result = gson.fromJson(getResponse(),
MyClassResponse.class);
for (int x = 0; x < result.ids[0].id.length; x++) {
myClass = new MyClass();
myClass.setStringOne(result.ids[0].fieldOne);
myClass.setStringTwo(result.ids[0].fieldTwo);
myClassList.add(x, myClass);
}
}
Gson gsonOut = new Gson();
String jsonString = gsonOut.toJson(myClassList);
JsonArray jsonArray = new JsonParser().parse(jsonString).getAsJsonArray();
JSONObject response = new JSONObject();
response.put("CustomStructure", jsonArray);
//pass back custom JSON body
答案 0 :(得分:0)
使用此逻辑:
答案 1 :(得分:0)
这是我实施它的方式:
/***Code to execute threads***/
Thread[] threads = new Thread[ids.size()];
for (int i = 0; i < ids.size(); i++) {
JSONObject p = (JSONObject)id.get(i);
id = p.get("ID").toString();
threads[i] = new Thread(new DoThread(id));
threads[i].start();
}
for(int i = 0; i < id.size(); i++) {
threads[i].join();
}
/*****************************/
public class DoThread implements Runnable {
private String id;
public DoThread(String id) {
this.id = id;
}
public void run() {
//Do Work
}
}