如何在Java中进行并行处理/多线程处理以调用REST端点

如何在Java中进行并行处理/多线程处理以调用REST端点,java,multithreading,rest,Java,Multithreading,Rest,我要实现并行处理,一次调用4个微服务调用。其中我有一个16的输入,其中每个微服务应该消耗4个进程 for (int i = 0; i < 16; i++) { if (m == i) { LOGGER.info("Inside If condition"); String jsonMes1 = jsonArr.get(i).toString(); URL url = new URL("http://localhost:8086/myS

我要实现并行处理,一次调用4个微服务调用。其中我有一个16的输入,其中每个微服务应该消耗4个进程

for (int i = 0; i < 16; i++) {
    if (m == i) {
        LOGGER.info("Inside If condition");
        String jsonMes1 = jsonArr.get(i).toString();
        URL url = new URL("http://localhost:8086/myService");

        conn = (HttpURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/json");

        OutputStream os = conn.getOutputStream();
        os.write(jsonMessage.getBytes());
        os.flush();

        if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
            LOGGER.info(" FAILED ");
        } else {
            LOGGER.info("  SUCESSFULLY PROCESSED ");
        }
        n = m;
        n++;
    } else if (n == i) {
        //Same process in different port
        o = n;
        o++;
    } else if (o == i) {
        //Same process in different port
        p = o;
        p++;
    } else if (p == i) {
        //Same process in different port
        m = p;
        m++;
    }
for(int i=0;i<16;i++){
如果(m==i){
LOGGER.info(“内部如果条件”);
字符串jsonMes1=jsonArr.get(i).toString();
URL=新URL(“http://localhost:8086/myService");
conn=(HttpURLConnection)url.openConnection();
连接设置输出(真);
conn.setRequestMethod(“POST”);
conn.setRequestProperty(“内容类型”、“应用程序/json”);
OutputStream os=conn.getOutputStream();
write(jsonMessage.getBytes());
os.flush();
if(conn.getResponseCode()!=HttpURLConnection.HTTP\u确定){
LOGGER.info(“失败”);
}否则{
LOGGER.info(“成功处理”);
}
n=m;
n++;
}else如果(n==i){
//不同端口中的相同进程
o=n;
o++;
}else如果(o==i){
//不同端口中的相同进程
p=o;
p++;
}else如果(p==i){
//不同端口中的相同进程
m=p;
m++;
}

相同的重复代码,如果条件在不同的端口上运行,其他3个都是相同的。但问题是,如果第一个请求完成,然后第二个请求正在处理,但我需要以并行方式进行处理。我只需要在迭代JSON数组中的对象时并行处理。请建议如何以并行方式实现这一点方式

假设您希望在rest调用后同步继续:将可变部分计算出来并放入列表中,然后使用并行流,例如:

Arrays.asList("port1", "port2", "port3").parallelStream()
   .forEach(port -> performRestCall(port));
或者,您也可以使用
ForkJoinPool


注意:本着干净编码的精神,避免使用像n、m、n、p这样的变量。

您尝试过什么吗?它是同步处理的,但我需要异步进行t process 4 process以完成16次处理您能建议我如何以异步方式处理多个处理吗?您不想等待其他调用重新执行吗rn并继续执行?换句话说,您只想以一种“火而忘”的方式生成工作线程?