如何进行并行处理/多线程处理以在Java

时间:2017-05-19 14:47:54

标签: 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/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++;
    }

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

1 个答案:

答案 0 :(得分:1)

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

Arrays.asList("port1", "port2", "port3").parallelStream()
   .forEach(port -> performRestCall(port));

或者您也可以使用ForkJoinPool

P.S。本着干净编码的精神,避免使用n,m,n,p等变量。

相关问题