1 回答
TA贡献1802条经验 获得超6个赞
int[][] array = new int[N][M]利用二维数组调用array[n]将返回第 n 行的事实,您可以将该行传递给每个线程:
int[][] array = { {1,2,3}, {4,5,6}, {7,8,9}, {10,11,12,13,14,15} };
ExecutorService threadPool = Executors.newFixedThreadPool(array.length);
for(int i = 0; i < array.length; i++) {
final int finalI = i;
threadPool.submit(() -> {
int[] row = array[finalI];
System.out.println(Thread.currentThread().getName() + ": " + Arrays.toString(row));
for(int j = 0; j < row.length; j++) {
row[j] *= 2;
}
});
}
threadPool.shutdown();
while(!threadPool.isTerminated()) {
Thread.sleep(20);
}
for(int i = 0; i < array.length; i++) {
int[] row = array[i];
for(int j = 0; j < row.length; j++) {
System.out.print(row[j] + ", ");
}
System.out.println();
}
将打印:
pool-1-thread-4: [10, 11, 12, 13, 14, 15]
pool-1-thread-1: [1, 2, 3]
pool-1-thread-2: [4, 5, 6]
pool-1-thread-3: [7, 8, 9]
2, 4, 6,
8, 10, 12,
14, 16, 18,
20, 22, 24, 26, 28, 30,
添加回答
举报