【问题标题】:How do I pass different value to each thread in ExecutorService?如何将不同的值传递给 ExecutorService 中的每个线程?
【发布时间】:2021-09-12 08:04:57
【问题描述】:

假设我有一个数组num_array = [0,1,2,3,4...30]

我有一个这样的多线程函数

static void multiThreadFunct (int[] num_array) {
    ExecutorService executor = Executors.newFixedThreadPool(25);
    try {
        Runnable r = new functToBeMultithreadded(arg1, arg2);
        executor.execute(r);
    } catch (Exception e) {
        System.out.println("err");
    }
    executor.shutdown();
}    

我想知道如何将num_array[0] 传递给thread 1num_array[1] 传递给thread 2 ... num_array[24] 传递给thread 25

【问题讨论】:

    标签: java arrays multithreading executorservice runnable


    【解决方案1】:

    只需遍历数组并传递每个可运行元素:

    ExecutorService executor = Executors.newFixedThreadPool(25);
    for (int num : num_array) {
        try {
            Runnable r = new FunctToBeMultithreadded(num);
            executor.execute(r);
        } catch (Exception e) {
            ...
        }
    }
    executor.shutdown();
    

    请注意,您不应假设元素的顺序将对应于池中创建的线程的顺序。这取决于实现。

    【讨论】:

    • 这不会为num_array 中的每个数字创建 25 个线程吗?
    • @ShashankSetty 这取决于(至少取决于 runnable 的作用)。 execute 方法的Javadoc 声明:“该命令可以在新线程、池线程或调用线程中执行,由 Executor 实现自行决定。”
    猜你喜欢
    • 2020-09-22
    • 2012-10-21
    • 1970-01-01
    • 2022-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多