[英]Java - Threading HttpUrlConnection calls
I have a custom service module where I pass up a JSON body, containing an array of IDs. 我有一个自定义服务模块,其中传递了一个JSON主体,其中包含ID数组。 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.
我必须遍历这些ID,并使用每个ID进行单独的Web服务调用以获得响应主体,然后将这些响应聚合到自定义JSON结构中。 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.
我已经完成所有工作,但是我想实现线程化(或其某种方式)来异步而不是连续进行HTTP调用。 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
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.