简体   繁体   English

Java-线程HttpUrlConnection调用

[英]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: 使用以下逻辑:

  • Create a Runnable that does what your loop is doing, constructor taking the individual JSONObject as input. 创建一个执行循环操作的Runnable,构造函数将单个JSONObject作为输入。
  • Store the output MyClassResponse as a member variable in your runnable. 将输出MyClassResponse作为成员变量存储在您的runnable中。
  • Have a list of threads and List of Runnable declared outside the loop 在循环外声明线程列表和Runnable列表
  • Create the thread and runnable inside the loop and add it to the lists 在循环内创建线程并运行该线程并将其添加到列表中
  • start the thread inside the loop 启动循环内的线程
  • After the loop call Thread.join on each of the threads in the list of threads (This makes this thread wait till the threads are completed.) 在循环后,在线程列表中的每个线程上调用Thread.join(这使该线程等待直到线程完成。)
  • create your MyClassList from the list of runnables once all the join statements have returned back 一旦所有的join语句都返回了,就从可运行对象列表中创建MyClassList。

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.

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