Java并行方阵乘法调整矩阵尺寸为4x4时报ArrayIndexOutOfBoundsException求助
问题原因
- 线程数组
Threads硬编码为3x3大小,当M/N调整为4后,循环访问下标i>=3或j>=3时直接触发越界 - 矩阵A、B的维度硬编码,当前A为3行2列、B为2行3列,二者相乘的合法结果维度只能是3行3列,M/N改为4后访问A的第4行、B的第4列都会越界
- 工作线程的计算逻辑硬编码为只累加2项乘积,仅支持A的列数为2的场景,矩阵维度变化后计算逻辑失效
- 主线程未等待所有工作线程执行完成就打印结果矩阵C,会得到未计算完成的错误值
修复方案
所有数组维度改为动态参数定义,不要硬编码常量;工作线程计算逻辑改为循环累加适配任意合法矩阵维度;新增线程等待逻辑保证计算完成后再打印结果。修改后可通过调整M、K、N三个参数灵活适配不同大小的矩阵(矩阵相乘要求A的列数=B的行数=K)。
修改后代码
public class ParallelMultiplier { // 矩阵A:M行 K列;矩阵B:K行 N列;结果矩阵C:M行 N列 public static int M = 4; public static int K = 2; public static int N = 4; // 调整矩阵数值时只需匹配上方M/K/N的维度规则即可 public static int[][] A = {{1, 4}, {2, 5}, {3, 6}, {4, 7}}; public static int[][] B = {{8, 7, 6, 5}, {5, 4, 3, 2}}; public static int[][] C = new int[M][N]; // 线程数组维度动态匹配矩阵大小,不再硬编码 public static WorkerThread[][] Threads = new WorkerThread[M][N]; public static void main(String[] args) throws InterruptedException { for (int i = 0; i < M; i++) { for (int j = 0; j < N; j++) { Threads[i][j] = new WorkerThread(i, j, A, B, C, K); Threads[i][j].start(); } } // 等待所有工作线程执行完成再打印结果 for (int i = 0; i < M; i++) { for (int j = 0; j < N; j++) { Threads[i][j].join(); } } System.out.println("Elements of Matrix C:"); for (int i = 0; i < M; i++) { for (int j = 0; j < N; j++) { System.out.println("[" + i + "," + j + "] = " + C[i][j]); } } } }
class WorkerThread extends Thread { private int row; private int col; private int[][] A; private int[][] B; private int[][] C; private int k; public WorkerThread(int row, int col, int[][] A, int[][] B, int[][] C, int k) { this.row = row; this.col = col; this.A = A; this.B = B; this.C = C; this.k = k; } public void run() { int sum = 0; // 循环累加适配任意K值,不再硬编码计算项数 for (int t = 0; t < k; t++) { sum += A[row][t] * B[t][col]; } C[row][col] = sum; } }
内容的提问来源于stack exchange,提问作者Kozinski123
相关产品推荐
相关产品推荐

