Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/351.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 在矩阵中实现线程数组_Java_Multithreading_Performance_Matrix - Fatal编程技术网

Java 在矩阵中实现线程数组

Java 在矩阵中实现线程数组,java,multithreading,performance,matrix,Java,Multithreading,Performance,Matrix,我的任务是制作一个项目,获取两个矩阵的输入维度,让用户选择他希望对这些矩阵执行的操作,并输出结果矩阵。增加的扭曲是,它必须并行进行。对于每个元素/单元,结果矩阵必须有一个线程。例如,2x2和另一个2x2矩阵输出4个元素。因此,必须有4个线程,每个线程对每个元素执行操作。以下是我的矩阵代码: public class Matrix { public int row,column; private double [][] matrixElements;

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

这是我的用户输入代码

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


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

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

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

139 is not dividable by 8
因此,让我们做一些清理,找出其中的区别:

139%8=3
()

所以现在你知道你有额外的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];

            }

        }
for(int i=0;i
您需要做什么,您将创建并告诉他们从哪里开始,从哪里结束:

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=start;i
然后你可以做数学运算,做类似的事情:

for(int i = 0; i < threadCount;i++){
            int start = i * step;
            int end = start  + step;

   new Thread(new Add(....)).run();


}
for(int i=0;i
我会更改代码结构,否则它可能太复杂,无法与线程合并

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

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);
}

}
导入java.util.concurrent.ExecutorService;
导入java.util.concurrent.Executors;
公共类矩阵{
@功能接口
接口矩阵运算{
公共无效应用(矩阵m1、矩阵m2、矩阵m3、整数i、整数j);
}
私有最终静态矩阵操作addFunc=(m1,m2,m3,i,j)->{
双值=m1.get(i,j)+m2.get(i,j);
m3.设定值(i,j,值);
};
私有最终静态矩阵运算subtractFunc=(m1,m2,m3,i,j)->{
双值=m1.get(i,j)+m2.get(i,j);
m3.设定值(i,j,值);
};
私有最终静态矩阵操作productFunc=(m1,m2,m3,i,j)->{
双值=0;
for(int index=0;indeximport 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);
}

}