我有一张10张地图的清单,这些地图都要求进行后期通话。我需要迭代这些映射并使用并发在Java中发出POST请求。
我希望每个线程同时发出两个发布请求,并且我不想等待这些响应。我只需要使用5个线程并行处理这10个请求即可。
我的问题是它没有遇到并行请求。它正在等待响应,并为每个请求占用一个线程。我想同时接受两个线程请求。
我的代码是:
for (int i = 0; i < finalList.size(); i++) {
String eachJsonReq = finalList.get(i);
Runnable worker = new MyRunnable(api_url,eachJsonReq);
executor.execute(worker);
}
executor.shutdown();
public static class MyRunnable implements Runnable {
private final String url;
private final String jsonInputData;
MyRunnable(String url,String jsonInputData) {
this.url = url;
this.jsonInputData = jsonInputData;
}
public void run() {
try {
doPost(url,jsonInputData);
} catch (Exception e) {
e.printStackTrace();
}
}
}
public static void doPost(String url, String data) throws Exception {
URL urlObj = new URL(url);
HttpURLConnection conn = (HttpURLConnection) urlObj.openConnection();
conn.setDoOutput(true);
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestMethod("POST");
DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
wr.writeBytes(data);
//OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
//writer.write(data);
System.out.println("Hitted url is "+url+" with data is "+data);
wr.flush();
wr.close();
conn.disconnect();
}