我正在嘗試創建一個Java程序與矩陣乘法的線程。這是源代碼:矩陣乘法與線程Java
import java.util.Random;
public class MatrixTest {
//Creating the matrix
static int[][] mat = new int[3][3];
static int[][] mat2 = new int[3][3];
static int[][] result = new int[3][3];
public static void main(String [] args){
//Creating the object of random class
Random rand = new Random();
//Filling first matrix with random values
for (int i = 0; i < mat.length; i++) {
for (int j = 0; j < mat[i].length; j++) {
mat[i][j]=rand.nextInt(10);
}
}
//Filling second matrix with random values
for (int i = 0; i < mat2.length; i++) {
for (int j = 0; j < mat2[i].length; j++) {
mat2[i][j]=rand.nextInt(10);
}
}
try{
//Object of multiply Class
Multiply multiply = new Multiply(3,3);
//Threads
MatrixMultiplier thread1 = new MatrixMultiplier(multiply);
MatrixMultiplier thread2 = new MatrixMultiplier(multiply);
MatrixMultiplier thread3 = new MatrixMultiplier(multiply);
//Implementing threads
Thread th1 = new Thread(thread1);
Thread th2 = new Thread(thread2);
Thread th3 = new Thread(thread3);
//Starting threads
th1.start();
th2.start();
th3.start();
th1.join();
th2.join();
th3.join();
}catch (Exception e) {
e.printStackTrace();
}
//Printing the result
System.out.println("\n\nResult:");
for (int i = 0; i < result.length; i++) {
for (int j = 0; j < result[i].length; j++) {
System.out.print(result[i][j]+" ");
}
System.out.println();
}
}//End main
}//End Class
//Multiply Class
class Multiply extends MatrixTest {
private int i;
private int j;
private int chance;
public Multiply(int i, int j){
this.i=i;
this.j=j;
chance=0;
}
//Matrix Multiplication Function
public synchronized void multiplyMatrix(){
int sum=0;
int a=0;
for(a=0;a<i;a++){
sum=0;
for(int b=0;b<j;b++){
sum=sum+mat[chance][b]*mat2[b][a];
}
result[chance][a]=sum;
}
if(chance>=i)
return;
chance++;
}
}//End multiply class
//Thread Class
class MatrixMultiplier implements Runnable {
private final Multiply mul;
public MatrixMultiplier(Multiply mul){
this.mul=mul;
}
@Override
public void run() {
mul.multiplyMatrix();
}
}
我只是想在Eclipse和它的作品,但現在我想創建一個程序的另一個版本,在其中,我使用一個線程,我將不得不在每個單元結果矩陣。例如,我有兩個3x3矩陣。所以結果矩陣將是3x3。然後,我想使用9個線程來計算結果矩陣的9個單元格中的每一個。
任何人都可以幫助我嗎?
問候
我確定有人可以幫助你!他們幫助你達成什麼目標? –
我需要一些有關線程同步的幫助,因爲在那種情況下,我只使用3個線程。在另一個程序中,我想使用9個或更多的線程(當我將有大於3x3的矩陣時)爲每個單元格分配一個線程。我認爲我需要創建一個單元類,但目前我沒有其他想法 – WhatElse88
那麼你是否正在尋找一種創建'n'線程的方式,其中'n'是單元的數量? –