如何解决如何将不同的值传递给 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();
请注意,您不应假设元素的顺序与池中创建的线程的顺序相对应。这取决于实现。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。