【问题标题】:Implementing a Thread Array in Matrix在矩阵中实现线程数组
【发布时间】:2025-12-26 20:20:08
【问题描述】:

我的任务是创建一个项目,该项目采用两个矩阵的输入维度,并让用户选择他希望对这些矩阵执行的操作并输出结果矩阵。增加的转折是它必须并行完成。对于每个元素/单元格,结果矩阵必须有一个线程。例如 2x2 和另一个 2x2 矩阵输出 4 个元素。所以必须有 4 个线程,每个线程对每个元素执行操作。这是我的矩阵代码:

 public class Matrix {
        public int row,column;
        private double [][] matrixElements;

        public Matrix (int rows, int columns){
            this.row= rows;
            this.column = columns;
            matrixElements = new double[row][column];
            populatematrix(-100,100);
        }


        public Matrix(double[][] matrixArray){
            this.row = matrixArray.length;
            this.column = (matrixArray[0]).length;
            matrixElements = new double [row][column];
            for (int i=0; i<row;i++){
                for (int j=0; j<column;j++){
                     matrixElements[i][j] = matrixArray[i][j];
                }
            }
        }
         private void populatematrix(int min, int max){
             Random randnum = new Random();
             Random rand = new Random();

              for (int i=0; i<row; i++){
                  for (int j= 0;i<row;i++){
                      matrixElements[i][j] = rand.nextInt((max - min) + 1) + min;
                  }
              }
         }
         public Matrix add(Matrix otherMatrix){
             double[][] resultMatrixArray = new double[this.row][this.column];
             for (int i=0; i<row; i++){
                 for (int j=0; j<column; j++){ 
                     resultMatrixArray[i][j] = this.matrixElements[i][j] + otherMatrix.matrixElements[i][j];

                 }

             }
             return new Matrix(resultMatrixArray);
         }

         public Matrix subtract(Matrix otherMatrix){
             double[][] resultMatrixArray = new double[row][column];

             for (int i=0; i<row; i++){ 
                 for (int j=0; j<column; j++){
                     resultMatrixArray[i][j] = this.matrixElements[i][j] - otherMatrix.matrixElements[i][j];
                 }
             } 
             return new Matrix(resultMatrixArray);

         }




        public Matrix dotProduct(Matrix otherMatrix){

            double[][] resultMatrixArray = new double [row][column];

            double sum = 0;

            if (this.column !=otherMatrix.row)
                System.out.println("\n\n Matrices Multiplication is not possible...Invalid Dimensions...\n\n");
            else {
                for (int c=0; c<this.row;c++){
                    for (int d = 0; d<otherMatrix.column;d++){
                        for (int k = 0; k<otherMatrix.row; k++){
                            sum = sum+((this.matrixElements[c][k])*(otherMatrix.matrixElements[k][d]));
                        }
                        resultMatrixArray[c][d]=sum;
                        sum = 0;
                    }
                }
            }
            return new Matrix(resultMatrixArray);
        }

        public String getPrintableMatrix(){
            String result ="";

            for (double[] roww: matrixElements){
                for (double j:roww){
                    result +=""+j + "";

                }
                result +="\n";

            }
            return result;
        }
}

这是我用于查找任何操作的矩阵结果的方法的代码。

public class MatrixOperations {
    public static void main(String args[]){
        int row1,col1,row2,col2;

        Scanner sc = new Scanner(System.in);

        System.out.print("\n\n Input Matrix 1 dimensions (ROWS space COLUMNS):");
        row1= sc.nextInt();
        col1 = sc.nextInt();

        System.out.print("\n\n Input Matrix 2 dimensions (ROWS space COlUMNS):");
        row2= sc.nextInt();
        col2 = sc.nextInt();

        int operation;

         System.out.print("\n\n Select the operation to executed: 1. Add 2. Subtract 3. Multiply \n > ");
         operation = sc.nextInt();

         Matrix result;
         Matrix m1 = new Matrix(row1, col1);
         Matrix m2 = new Matrix(row2, col2);

         Thread myThreads[] = new Thread[Matrix.row];
        switch(operation){
            case 1:
                result = m1.add(m2);
                System.out.println("\n\n First Matrix: \n " + m1.getPrintableMatrix());
                System.out.println("\n\n Second Matrix: \n " + m2.getPrintableMatrix());
                System.out.println("\n\n Resultant Matrix: \n " + result.getPrintableMatrix());

                break;

            case 2:
                result = m1.subtract(m2);

                 System.out.println("\n\n First Matrix: \n " + m1.getPrintableMatrix());
                 System.out.println("\n\n Second Matrix: \n " + m2.getPrintableMatrix());
                 System.out.println("\n\n Resultant Matrix: \n " + result.getPrintableMatrix());


                 break;

            case 3:

                result = m1.dotProduct(m2);

                 System.out.println("\n\n First Matrix: \n " + m1.getPrintableMatrix());
                 System.out.println("\n\n Second Matrix: \n " + m2.getPrintableMatrix());
                 System.out.println("\n\n Resultant Matrix: \n " + result.getPrintableMatrix());

                 break;

            default: System.out.println("\nInvalid operation......\n");break;
        }

        System.out.print("\n\n");
    }

}

这是我的用户输入代码。

我的问题是如何使这种平行。这是我的第一个并行项目,我知道我必须使用一组线程,但我不知道将它们放在哪里,我尝试了多种方法,似乎没有人能帮助我。

我知道它需要一个线程数组,所需的数组数量是输出矩阵中的元素数量,但我不知道在哪里或如何实现该数组,因为我在多种方式中都遇到了错误试过了。

【问题讨论】:

    标签: java multithreading performance matrix


    【解决方案1】:

    我会更改代码结构,否则可能太复杂而无法与线程结合。

    • 将矩阵元素(“+”、“-”、“*”)上的原子操作移动到相应的功能接口中
    • 创建一个单独的函数,处理matrix、otherMatrix和需要的操作,并把所有的并发隐藏在里面
    • 在上述函数中,启动 ExecutorService 并使用所需数量的线程(下例中为 4 个),并在提交所有任务后将其关闭
    • 在应用操作之前识别结果矩阵行/列计数。 (*) 请注意,您的代码中可能存在错误,dotProduct 函数结果矩阵大小不是必需的new double [row][column]

    请看下面的代码

    import java.util.concurrent.ExecutorService;
    import java.util.concurrent.Executors;
    
    public class Matrix {
    
    @FunctionalInterface
    interface MatrixOperation<Matrix, Integer> {
        public void apply(Matrix m1, Matrix m2, Matrix m3, Integer i, Integer j);
    }
    private final static MatrixOperation<Matrix, Integer> addFunc = (m1, m2, m3, i, j) -> {
        double value = m1.get(i, j) + m2.get(i, j);
        m3.set(i, j, value);
    };
    private final static MatrixOperation<Matrix, Integer> subtractFunc = (m1, m2, m3, i, j) -> {
        double value = m1.get(i, j) + m2.get(i, j);
        m3.set(i, j, value);
    };
    private final static MatrixOperation<Matrix, Integer> productFunc = (m1, m2, m3, i, j) -> {
        double value = 0;
        for (int index = 0; index < m1.column; index++) {
            value += m1.get(i, index) * m2.get(index, j);
        }
        m3.set(i, j, value);
    };
    //Set number of threads
    private final static int threadCount = 4;
    
    public int row, column;
    private double[][] matrixElements;
    
    
    public Matrix(int rows, int columns) {
        this.row = rows;
        this.column = columns;
        matrixElements = new double[row][column];
    }
    
    
    public Matrix(double[][] matrixArray) {
        this.row = matrixArray.length;
        this.column = (matrixArray[0]).length;
        matrixElements = new double[row][column];
        for (int i = 0; i < row; i++) {
            for (int j = 0; j < column; j++) {
                matrixElements[i][j] = matrixArray[i][j];
            }
        }
    }
    
    public double get(int i, int j) {
        return matrixElements[i][j];
    }
    
    public void set(int i, int j, double value) {
        matrixElements[i][j] = value;
    }
    
    private Matrix operation(Matrix m2, Matrix result, MatrixOperation<Matrix, Integer> operator) {
        ExecutorService executor = Executors.newFixedThreadPool(threadCount);
        for (int i = 0; i < result.row; i++) {
            for (int j = 0; j < result.column; j++) {
                final int i1 = i;
                final int j1 = j;
                executor.submit(new Runnable() {
                    @Override
                    public void run() {
                        operator.apply(Matrix.this, m2, result, i1, j1);
                    }
                });
    
            }
        }
        try {
            executor.shutdown();
            executor.awaitTermination(Long.MAX_VALUE, TimeUnit.MILLISECONDS);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return result;
    }
    
    public Matrix add(final Matrix m2) {
        if (this.row != m2.row || this.column != m2.column) {
            throw new IllegalArgumentException();
        }
        return operation(m2, new Matrix(row, column), addFunc);
    }
    
    public Matrix subtract(Matrix m2) {
        if (this.row != m2.row || this.column != m2.column) {
            throw new IllegalArgumentException();
        }
        return operation(m2, new Matrix(row, column), subtractFunc);
    }
    
    
    public Matrix dotProduct(Matrix m2) {
        if (this.column != m2.row) {
            throw new IllegalArgumentException();
        }
        return operation(m2, new Matrix(row, m2.column), productFunc);
    }
    
    }
    

    几个提示:

    • 在这种情况下,线程数大于机器上的内核数是没有意义的,这会使代码变慢。
    • (!) ExecutorService.shutdown() 强制执行器完成所有正在运行的任务而不接受新任务。 ExecutorService.awaitTermination 停止主线程,直到所有任务完成。即,结果矩阵将 在返回之前完全构建。
    • 只要不同的线程从matrix和otherMatrix中读取,在计算过程中一定不能更新,并写入结果矩阵的不同位置(i,j),代码是线程安全的。

    【讨论】:

    • 您好,也感谢您帮助我解决这个问题,我是线程和并行编程的新手,这对我帮助非常大,谢谢您
    【解决方案2】:

    好吧,很公平,看来你付出了很大的努力并愿意学习更多,所以这是我的 2 美分:

    你有一个农场。 139 米 长。每年你自己收集(比方说)土豆。您每米花费 1 小时。因此,如果您每天工作 12 小时,每年收获大约需要 12 天 (139/12)。 然后你赚了一些钱,你雇了 8 家伙。您将如何平分土地:

    139 is not dividable by 8
    

    所以让我们做一些清理并找出不同之处:

    139 % 8 = 3 (modulo)

    所以现在您知道您有额外的 3 仪表可以自己处理。其他人可以这样处理:

    (Total - Difference) / workers = meters per worker
    

    如果我们填空:

    (139 - 3) / 8 = 17
    

    所以我们知道每个工人将工作 17 米。等等,但他们都不应该在前 17 米工作!!!我们需要平分

    所以我们会给每个worker一个id:

    {0,1,2,3,4,5,6,7}
    

    然后我们将通过他们的 id 告诉工人从哪里开始和在哪里结束:

      start = id * step
      end = start + step
    

    这将导致开始,结束:

      worker 0 will work: 0 until 17 (not including 17, 0 indexed ;))
      worker 1 will work: 17 until 34
      worker 2 will work: 34 until 51
      worker 3 will work: 51 until 68
      worker 4 will work: 68 until 85
      worker 5 will work: 85 until 102
      worker 6 will work: 102 until 119
      worker 7 will work: 119 until 136
    
      and you = 136 until 139 (3 meter)
    

    既然你有多维数组,你就有这样的内部循环:

    for (int i = 0; i < row; i++) {
                for (int j = 0; j < column; j++) {
                    resultMatrixArray[i][j] = this.matrixElements[i][j] + otherMatrix.matrixElements[i][j];
    
                }
    
            }
    

    您需要做的是创建threads 并告诉他们每个人从哪里开始和从哪里结束

    for (int i = start; i < end; i++) {
                for (int j = 0; j < columns; j++) {
                    resultMatrixArray[i][j] = thisMatrix[i][j] + otherMatrix[i][j];
    
                }
    
            }
    

    然后你可以做数学运算并做类似的事情:

    for(int i = 0; i < threadCount;i++){
                int start = i * step;
                int end = start  + step;
    
       new Thread(new Add(....)).run();
    
    
    }
    

    【讨论】:

    • 非常感谢!感谢您一直以来对我的帮助,它给了我一个全新的视角,现在我终于知道该怎么做了,谢谢!