我必须创建一个程序来模拟并发矩阵加法和乘法。我意识到,如果我有 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);
我可以确保add
在multiply
之前完成,反之亦然?感谢您的帮助。
最佳答案
一般来说,以下是使用原始线程的方法:
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/