gpt4 book ai didi

java - 在矩阵中实现线程数组

转载 作者:行者123 更新时间:2023-12-03 13:09:21 25 4
gpt4 key购买 nike

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

}

这是我的用户输入代码。

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

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

最佳答案

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

  • 将矩阵元素(“+”、“-”、“*”)上的原子操作移动到相应的功能接口(interface)
  • 创建一个单独的函数,处理矩阵、其他矩阵和所需的操作,并将所有并发隐藏在
  • 在上面的函数中,启动 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),代码是线程安全的。
  • 关于java - 在矩阵中实现线程数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41233223/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com