我必须创建一个程序来模拟并发矩阵的加法和乘法。我意识到如果我有3个矩阵:A,B和C,并且我想计算A + B = C或A * B = C,那么我可以创建的最大线程数量为(C中的行)*( C中的列),因为矩阵C中的每个最终位置都可以独立于其他位置进行计算。矩阵乘法/并行并发
我真正的问题是:如果我有它拥有一些方法multiply(), add(), print()
一个接口MatrixMath
,我怎么能保证当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
创建一个可运行的,将计算所需的特定行和列的总和,并把它变成矩阵C.该行和列我会让类似于MatrixProductThread
的可运行类。
someMatrixMathObject.add(A,B,C);
someMatrixMathObject.multiply(A,B,C);
那我可以保证add
完成的multiply
,反之亦然之前:
如何确保,如果我有什么想法?感谢您的任何帮助。
将任务推送到'Collection>'中,然后将所有这些任务放入'Exec utorService.invokeAll' - 这将在完成时返回。附:你真的认为值得使用线程来添加每一对数字吗? (提示;不,不是)。 –
我会倾听@BoristheSpider,但如果你想自己处理所有事情,那么你应该阅读[this](http://javahowto.blogspot.no/2007/05/when-to-join-threads.html)文章关于加入线程。 “假设我需要产生多个线程来完成这项工作,并且只有在所有这些完成后才能继续下一步......关键是要使用Thread.join()方法。” – atomman
@BoristheSpider谢谢你的提示,我会研究一下!而现实:不,我不认为这是值得使用多个线程。这是一个大学任务,但其中的重点是要在这种情况下最大限度地控制不同的线程,而不一定创建一个现实的场景。 –