如何将不同的值传递给 ExecutorService 中的每个线程?

How do I pass different value to each thread in ExecutorService?

假设我有一个数组 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 1 并将 num_array[1] 传递给 thread 2 ... num_array[24] 传递给 thread 25

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

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

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