java - 矩阵乘法/加法的并发

标签 java matrix concurrency

我必须创建一个程序来模拟并发矩阵加法和乘法。我意识到,如果我有 3 个矩阵:A、B 和 C,并且我想计算 A+B = C 或 A*B = C,那么我可以创建的最大线程数为 (C 中的行) * ( C 中的列),因为矩阵 C 中的每个最终位置都可以独立于其他位置进行计算。

我真正的问题是:如果我有一个接口(interface)MatrixMath,它有方法multiply()、add()、print(),我怎样才能确保当add()multiply() 方法终止,所有更改都已写入乘积或求和矩阵?

示例:

class MatrixMathImplementation implements MatrixMath {

  public void multiply(int[][]A, int[][]B, int[][]C) {
    //multiply the two matrices, spawning m*n threads
    //haven't coded this yet
  }

  public void add(int[][]A, int[][]B, int[][]C) {
      //add the two matricies, spawning m*n threads
      //First: Check that A, B, and C are all the same size
      if (A.length == B.length && A.length == C.length &&
        A[0].length == B[0].length && A[0].length == C[0].length) {

        for (int row=0; row < A.length; row++) {
          for (int col=0; col < A[0].length; col++) {
              new MatrixSumThread(A,B,C,row,col);
          }
        }    
      } else {
        System.out.println("ERROR: Arrays are not the same size.");
      }
    }
  }

  public void print() {
    //print the given matrix
    //doesn't need to be concurrent, haven't coded this yet either.
  }
}

在代码中,MatrixSumThread 创建一个 runnable,它将计算特定行和列所需的总和,并将其放入矩阵 C 中的该行和列中。我将制作一个类似的 runnable MatrixProductThread 的类。

关于如何确保我有的任何想法:

someMatrixMathObject.add(A,B,C);
someMatrixMathObject.multiply(A,B,C);

我可以确保addmultiply之前完成,反之亦然?感谢您的帮助。

最佳答案

一般来说,以下是使用原始线程的方法:

Thread t = new Thread(); // or subclass thereof
t.start();  // make sure to not start threads in the constructor; start explicitly
t.join();   // waits for the thread to finish

就你的情况而言:

// create a list to hold all your threads, above the for loops
List<MatrixSumThread> threads = new ArrayList<MatrixSumThread>();
// for() { ...
// make sure MatrixSumThread doesn't call start() in its constructor
MatrixSumThread t = new MatrixSumThread(A,B,C,row,col);
threads.add(t);
t.start();

然后,在完成 for 循环后,加入所有线程:

for (MatrixSumThread t in threads) {
  t.join();
}

关于java - 矩阵乘法/加法的并发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19552449/

相关文章:

java - 如何动态创建类 Java

java - aws s3 java sdk 下载 pdf 损坏

java - 正则表达式在 Java 类的单行/多行中查找注释

java - 如何从 Struts2/Servlet 中的 Apache Web 服务器获取客户端 IP 地址?

python - 从 tensorflow 中的向量构造成对矩阵

java - 如何使用锁包装器进行自动关闭?

javascript - JavaScript 是否保证是单线程的?

c++ - 从另一个子 vector 或子矩阵创建 boost::numeric::ublas vector

python - 如何在不使用Python库的情况下从单行输入生成矩阵?

java - 具有许多线程的 CyclicBarrier 性能较差 : Would a tree-like synchronization structure be an alternative?