I have a custom service module where I pass up a JSON body, containing an array of IDs. I have to iterate through these IDs and make a separate web service call with each ID to obtain a response body, then aggregate these responses into a custom JSON structure. I have that all working, but I'd like to implement threading (or some manner thereof) to make the HTTP calls asynchronously, rather than in succession. How would I implement threading in the following code:
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
Use this logic:
This is how I implemented it:
/***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
}
}
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.