2013-10-23 31 views
2

我必須創建一個程序來模擬併發矩陣的加法和乘法。我意識到如果我有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,反之亦然之前:

如何確保,如果我有什麼想法?感謝您的任何幫助。

+0

將任務推送到'Collection >'中,然後將所有這些任務放入'Exec utorService.invokeAll' - 這將在完成時返回。附:你真的認爲值得使用線程來添加每一對數字嗎? (提示;不,不是)。 –

+0

我會傾聽@BoristheSpider,但如果你想自己處理所有事情,那麼你應該閱讀[this](http://javahowto.blogspot.no/2007/05/when-to-join-threads.html)文章關於加入線程。 「假設我需要產生多個線程來完成這項工作,並且只有在所有這些完成後才能繼續下一步......關鍵是要使用Thread.join()方法。」 – atomman

+0

@BoristheSpider謝謝你的提示,我會研究一下!而現實:不,我不認爲這是值得使用多個線程。這是一個大學任務,但其中的重點是要在這種情況下最大限度地控制不同的線程,而不一定創建一個現實的場景。 –

回答

2

一般來說,這裏是你如何與原紗工作:

你的情況
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(); 
} 
+1

請包括更多細節並解釋OP如何使用上述代碼來解決手頭的情況。 – mavrosxristoforos

+0

夠公平的... – iluxa

+0

@iluxa謝謝;實現了類似的東西,它的工作 –