1 回答

TA貢獻(xiàn)1802條經(jīng)驗 獲得超6個贊
int[][] array = new int[N][M]利用二維數(shù)組調(diào)用array[n]將返回第 n 行的事實(shí),您可以將該行傳遞給每個線程:
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,
添加回答
舉報