Lets say I have an array num_array = [0,1,2,3,4...30]
and I have a multi-threading function like this
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(); }
I wanted to know how I can pass num_array[0]
to thread 1
and num_array[1]
to thread 2
… num_array[24]
to thread 25
Advertisement
Answer
Just loop over the array and pass each runnable the element:
ExecutorService executor = Executors.newFixedThreadPool(25); for (int num : num_array) { try { Runnable r = new FunctToBeMultithreadded(num); executor.execute(r); } catch (Exception e) { ... } } executor.shutdown();
Note that you should not assume the order of elements will correspond to the order of threads created in the pool. That’s implementation dependent.