Javaマルチスレッドプログラミングを調べます。私の仕事は、行列積を計算するマルチスレッドプログラムを実装することです。各スレッドは、結果として得られる行列の異なる行を担当します。タスクには、「メインプログラムでjoin()
を使用すると、すべてのスレッドが終了して結果のマトリックスを印刷するのを待つ」というメッセージが表示されます。
メインスレッドの最後の仕上げ方法
MatrixProduct.java結果の行列の行が独立して計算され
package multythreading;
import java.util.Arrays;
public class MatrixProduct {
public static Matrix a;
public static Matrix b;
static {
a = new Matrix(new int[][]{{1, 2, 3, 4, 5, 6, 7, 8, 9, 10},
{4, 5, 64, 5, 6, 7, 8, 9, 10, 11},
{7, 8, 94, 5, 6, 7, 8, 9, 10, 12},
{7, 8, 94, 5, 6, 7, 8, 9, 10, 13},
{4, 5, 64, 5, 6, 7, 8, 9, 10, 14},
});
b = new Matrix(new int[][]{{2, 1, 3},
{4, 2, 1},
{6, 4, 5},
{6, 4, 5},
{4, 2, 1},
{2, 1, 3},
{4, 2, 1},
{6, 4, 5},
{6, 4, 5},
{4, 2, 1}});
}
public static void main(String [] args) {
Thread[] threads = new Thread[a.getRowNum()];
for (int i = 0; i < threads.length; i++) {
threads[i] = new Thread(new ResultMatrixLine(i), "Line number " + i + " computation thread");
threads[i].start();
}
for (Thread t: threads) {
if (t.isAlive()) {
try {
System.out.println(t.getName() + " : " + t.getState() + " still alive");
t.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
System.out.println("All computation threads terminated and the resulting matrix is ready");
}
}
class ResultMatrixLine implements Runnable {
private int lineNumber;
public ResultMatrixLine(int lineNumber) {
this.lineNumber = lineNumber;
}
@Override
public void run() {
System.out.println("Line number = " + lineNumber + ": " + Arrays.toString(getResultLine()));
}
private int[] getResultLine() {
int[] result = new int[MatrixProduct.b.getColumnNum()];
for (int i = 0; i < MatrixProduct.b.getColumnNum(); i++)
for (int j = 0; j < MatrixProduct.a.getColumnNum(); j++)
result[i] += MatrixProduct.a.getMatrixElement(lineNumber, j)*MatrixProduct.b.getMatrixElement(j, i);
return result;
}
}
class Matrix {
private final int columnNum;
private final int rowNum;
private final int[][] matrix;
public Matrix(int[][] matrix) {
this.columnNum = matrix[0].length;
this.rowNum = matrix.length;
this.matrix = matrix;
}
public int getColumnNum() {
return columnNum;
}
public int getRowNum() {
return rowNum;
}
public int getMatrixElement(int columnIndx, int rowIndx) {
return matrix[columnIndx][rowIndx];
}
}
ので、私は気に唯一のことは、適切join()
でmain()
メソッドを使用している:
は、だからここに私のコードです。私は、メインスレッドの終わりに、他のすべてのスレッドを終了して、結果として得られるマトリックスが準備できることを意味します。最初の一見で私の決定はうまくいきますが、私はそれについてのコメントを見たいと思います。ここで
これはcodereviewに適していると思います... – ppeterka
't.join()'は、あなたが期待するように見えます。スレッド 't'が終了するのを待ちます。 –
JavaストリームAPIを見てください。このAPIはあなた自身で 'スレッド'を作成することはありません。副次的なこと:一般的なマルチスレッドとそれを行う方法とそれをやりなまない方法については、間違いなく読んでおく必要があります(つまり、マトリックス製品の単一行の計算など、小さなタスクごとに新しいスレッドを生成します)。あなたがTheadの管理を自分自身でやる必要がないようにするマルチスレッドの役に立つヘルパーは良いスタートです。 Javaの場合、これらは 'java.future'と新しい並列ストリームAPIです。 – AlexR