简体   繁体   English

使用 ExecutorService 使用一组 ip 地址管理并行线程的最佳方法

[英]Best approach to manage parallel threads with a set of ip addresses using ExecutorService

I have a set of 255 ip addresses to manage (xxx1 -> xxx255).我有一组 255 个 ip 地址要管理 (xxx1 -> xxx255)。 In Java if I check connection from my java mobile app with only one array of IP with a setTimeout(200) I could wait too much till finish all 255 ip addresses.在 Java 中,如果我检查来自我的 java 移动应用程序的连接,只有一组 IP 和setTimeout(200) ,我可以等待太多直到完成所有 255 个 ip 地址。 On the other hand if I connect to at least one of those ip address I have some other things to do.另一方面,如果我至少连接到 ip 地址中的一个,我还有一些其他事情要做。 So my goal to reduce wait time on check if connection test works or fails is to split in a group of 15 parallel threads working at the same time where inside each of them I check 17 ip addresses.因此,我减少检查连接测试是否有效的等待时间的目标是分成一组 15 个同时工作的并行线程,在每个线程中我检查 17 个 ip 地址。 In this way I made a class that implements Runnable where I execute something like:通过这种方式,我制作了一个实现 Runnable 的 class,我在其中执行如下操作:

HttpURLConnection con;
for(i=(currentThreadNumber*17)+1;i<(currentThreadNumber*17)+17;i++) { 
    String ipToCheckConnection = maskIP+"."+i;
    String loginURL = "http://" + ipToLogin + "/....";
    try {
        URL obj = new URL(loginURL);
        con = (HttpURLConnection) obj.openConnection();
        con.setRequestMethod("GET");
        con.setConnectTimeout(100);
        con.connect();
        int responseCode = con.getResponseCode();

        if (responseCode == HttpURLConnection.HTTP_OK) {
            con.disconnect();
            do something else with this IP....
        }

    } catch (java.net.SocketTimeoutException e) {
        continue;
    } catch (java.io.IOException e) {
        return;
    }
}

In my main function inside a button click event I implement:在我主要的 function 中,我实现了一个按钮点击事件:

ExecutorService executorService = Executors.newFixedThreadPool(15);

then I tried various way to execute parallel jobs calling the runnable class waiting all threads are finished before to continue and exit from button click event, like using CountDownLatch , .awaitTermination ... I tried also to use .invokeAll but it doesn't work with runnable but with callable... but I encounter the issue how to pass to runnable class current thread count like 0,1,2,3,..so I can pass to the for(...) inside runnable... What would be best approach to pass this current thread count like 0,1,2,3,.. to the runnable class?然后我尝试了各种方法来执行调用可运行 class 等待所有线程完成的并行作业,然后继续并退出按钮单击事件,例如使用CountDownLatch.awaitTermination ...我也尝试使用.invokeAll但它不起作用可运行但可调用...但我遇到了如何传递给可运行的问题 class 当前线程计数如 0,1,2,3,..所以我可以传递给可运行的for(...) ...将当前线程数(如 0、1、2、3、..)传递给可运行的 class 的最佳方法是什么? Or is there a better different way than using ExecutorService which I read everywhere it's the simplest way to work parallel threads with?...或者有没有比使用 ExecutorService 更好的不同方法,我到处都读到它是使用并行线程的最简单方法?...

Thanks!谢谢! Cheers干杯

You can do something as follows:您可以执行以下操作:

  • initialize the CountDownLatch and ExecutorService with the number of desired workers用所需工人的数量初始化CountDownLatchExecutorService
  • on the loop of assigning work to the workers pass the current task number在将工作分配给工人的循环中传递当前任务编号
  • each worker should also call countDownLatch.countDown();每个工人也应该调用countDownLatch.countDown(); after having terminated the work to signal that to the other workers that might be waiting在终止工作以向可能正在等待的其他工人发出信号之后
  • the main thread should call countDownLatch.await();主线程应该调用countDownLatch.await(); to wait for the remaining workers to finish their work.等待剩下的工人完成他们的工作。

The code could look like the following:代码可能如下所示:

public class WaitForAllToEnd {

    public static void main(String[] args) throws InterruptedException {
        final int total_threads = 15;
        CountDownLatch countDownLatch = new CountDownLatch(total_threads);
        ExecutorService executor = Executors.newFixedThreadPool(total_threads);
        for(int i = 0; i < total_threads; i++){
            final int thread_id = i;
            executor.execute(parallelWork(thread_id, countDownLatch));
        }
        countDownLatch.await();
        System.out.println("Exit");
        executor.shutdown();
    }

    private static Runnable parallelWork(int thread_id, CountDownLatch countDownLatch) {
        return () -> {
            try {
                // Some code logic
            } catch (InterruptedException e) {
                // Do Something
            }
            // Some code logic
            countDownLatch.countDown();
        };
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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