在Matrix中实现线程数组

时间:2016-12-20 00:39:54

标签: java multithreading performance matrix

我的任务是创建一个项目,该项目采用两个矩阵的输入维度,并让用户选择他希望对这些矩阵执行的操作并输出结果矩阵。增加的扭曲是它必须并行完成。对于每个元素/单元格,结果矩阵必须有一个线程。例如,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");
    }

}

这是我的用户输入代码。

我的问题是如何使这种并行。这是我的第一个并行项目,我知道我必须使用一系列线程,但我不知道放在哪里,我尝试了多种方式,没有人能够帮助我。

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

2 个答案:

答案 0 :(得分:0)

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

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

139 is not dividable by 8

所以,让我们做一些清理并发现差异:

139 % 8 = 3modulo

所以现在你知道你有额外的 3 米,你可以自己处理。其他人可以这样处理:

(Total - Difference) / workers = meters per worker

如果我们填写空白:

(139 - 3) / 8 = 17

所以我们知道每个工作人员都会为 17 米工作。等等,但是所有这些都不适用于前17米!!!我们需要平等分配

所以我们会给每个工人一个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();


}

答案 1 :(得分:0)

我会改变代码结构,否则它可能太复杂而无法与Threads合并。

  • 将矩阵元素上的原子操作(&#34; +&#34;,&#34; - &#34;,&#34; *&#34;)移动到相应的功能接口
  • 创建一个单独的函数,它处理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在所有任务完成之前停止主线程。即,结果矩阵将 在返回之前完全构建。
  • 只要不同的线程正在读取矩阵和其他矩阵(在计算过程中不得更新)并写入结果矩阵的不同位置(i,j),代码就是线程安全的。