[英]Matrix Multiplication with threads 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 個單元格中的每一個。
誰能幫我?
此致
您可以按如下方式創建n
線程(注意: numberOfThreads
是您要創建的線程數。這將是單元格的數量):
List<Thread> threads = new ArrayList<>(numberOfThreads);
for (int x = 0; x < numberOfThreads; x++) {
Thread t = new Thread(new MatrixMultiplier(multiply));
t.start();
threads.add(t);
}
for (Thread t : threads) {
t.join();
}
請使用新的 Executor 框架來創建線程,而不是手動做管道。
ExecutorService executor = Executors.newFixedThreadPool(numberOfThreadsInPool);
for (int i = 0; i < numberOfThreads; i++) {
Runnable worker = new Thread(new MatrixMultiplier(multiply));;
executor.execute(worker);
}
executor.shutdown();
while (!executor.isTerminated()) {
}
有了這段代碼,我認為我解決了我的問題。 我不在方法中使用同步,但我認為在這種情況下沒有必要。
import java.util.Scanner;
class MatrixProduct extends Thread {
private int[][] A;
private int[][] B;
private int[][] C;
private int rig,col;
private int dim;
public MatrixProduct(int[][] A,int[][] B,int[][] C,int rig, int col,int dim_com)
{
this.A=A;
this.B=B;
this.C=C;
this.rig=rig;
this.col=col;
this.dim=dim_com;
}
public void run()
{
for(int i=0;i<dim;i++){
C[rig][col]+=A[rig][i]*B[i][col];
}
System.out.println("Thread "+rig+","+col+" complete.");
}
}
public class MatrixMultiplication {
public static void main(String[] args)
{
Scanner In=new Scanner(System.in);
System.out.print("Row of Matrix A: ");
int rA=In.nextInt();
System.out.print("Column of Matrix A: ");
int cA=In.nextInt();
System.out.print("Row of Matrix B: ");
int rB=In.nextInt();
System.out.print("Column of Matrix B: ");
int cB=In.nextInt();
System.out.println();
if(cA!=rB)
{
System.out.println("We can't do the matrix product!");
System.exit(-1);
}
System.out.println("The matrix result from product will be "+rA+" x "+cB);
System.out.println();
int[][] A=new int[rA][cA];
int[][] B=new int[rB][cB];
int[][] C=new int[rA][cB];
MatrixProduct[][] thrd= new MatrixProduct[rA][cB];
System.out.println("Insert A:");
System.out.println();
for(int i=0;i<rA;i++)
{
for(int j=0;j<cA;j++)
{
System.out.print(i+","+j+" = ");
A[i][j]=In.nextInt();
}
}
System.out.println();
System.out.println("Insert B:");
System.out.println();
for(int i=0;i<rB;i++)
{
for(int j=0;j<cB;j++)
{
System.out.print(i+","+j+" = ");
B[i][j]=In.nextInt();
}
}
System.out.println();
for(int i=0;i<rA;i++)
{
for(int j=0;j<cB;j++)
{
thrd[i][j]=new MatrixProduct(A,B,C,i,j,cA);
thrd[i][j].start();
}
}
for(int i=0;i<rA;i++)
{
for(int j=0;j<cB;j++)
{
try{
thrd[i][j].join();
}
catch(InterruptedException e){}
}
}
System.out.println();
System.out.println("Result");
System.out.println();
for(int i=0;i<rA;i++)
{
for(int j=0;j<cB;j++)
{
System.out.print(C[i][j]+" ");
}
System.out.println();
}
}
}
如下考慮 Matrix.java 和 Main.java。
public class Matrix extends Thread {
private static int[][] a;
private static int[][] b;
private static int[][] c;
/* You might need other variables as well */
private int i;
private int j;
private int z1;
private int s;
private int k;
public Matrix(int[][] A, final int[][] B, final int[][] C, int i, int j, int z1) { // need to change this, might
// need some information
a = A;
b = B;
c = C;
this.i = i;
this.j = j;
this.z1 = z1; // a[0].length
}
public void run() {
synchronized (c) {
// 3. How to allocate work for each thread (recall it is the run function which
// all the threads execute)
// Here this code implements the allocated work for perticular thread
// Each element of the resulting matrix will generate by a perticular thread
for (s = 0, k = 0; k < z1; k++)
s += a[i][k] * b[k][j];
c[i][j] = s;
}
}
public static int[][] returnC() {
return c;
}
public static int[][] multiply(final int[][] a, final int[][] b) {
/*
* check if multipication can be done, if not return null allocate required
* memory return a * b
*/
final int x = a.length;
final int y = b[0].length;
final int z1 = a[0].length;
final int z2 = b.length;
if (z1 != z2) {
System.out.println("Cannnot multiply");
return null;
}
final int[][] c = new int[x][y];
int i, j;
// 1. How to use threads to parallelize the operation?
// Every element in the resulting matrix will be determined by a different
// thread
// 2. How may threads to use?
// x * y threads are used to generate the result.
for (i = 0; i < x; i++)
for (j = 0; j < y; j++) {
try {
Matrix temp_thread = new Matrix(a, b, c, i, j, z1);
temp_thread.start();
// 4. How to synchronize?
// synchronized() is used with join() to guarantee that the perticular thread
// will be accessed first
temp_thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return Matrix.returnC();
}
}
您可以使用Main.java
給出需要相乘的 2 個矩陣。
class Main {
public static int [][] a = {{1, 1, 1},
{1, 1, 1},
{1, 1, 1}};
public static int [][] b = {{1 },
{1 },
{1 }};
public static void print_matrix(int [][] a) {
for(int i=0; i < a.length; i++) {
for(int j=0; j< a[i].length; j++)
System.out.print(a[i][j] + " ");
System.out.println();
}
}
public static void main(String [] args) {
int [][] x = Matrix.multiply(a, b);
print_matrix(x); // see if the multipication is correct
}
}
簡單來說,你們需要做的是,
1) 創建 n 個(結果矩陣中沒有單元格)線程。 分配他們的角色。 (例如:考慮 MXN,其中 M 和 N 是矩陣。'thread1' 負責將 M 的 row_1 元素與 N 的 column_1 元素相乘並存儲結果。這是結果矩陣的 cell_1 的值。)
2) 啟動每個線程的進程。 (通過 start() 方法)
3) 等到所有線程完成它們的進程並存儲每個單元格的結果值。 因為這些過程應該在顯示結果矩陣之前完成。 (您可以通過 join() 方法以及其他可能性來做到這一點)
4) 現在,您可以顯示結果矩陣。
筆記:
1) 由於在本示例中,共享資源(M 和 N)僅用於只讀目的,因此您無需使用“同步”方法來訪問它們。
2)可以看到,在這個程序中,有一組線程在運行,它們都需要自己達到一個特定的狀態,才能繼續整個程序的下一步。 這種多線程編程模型稱為Barrier 。
在我的解決方案中,我分配給每個工人的行數numRowForThread
等於:(matA 的行數)/(線程數)。
public class MatMulConcur {
private final static int NUM_OF_THREAD =1 ;
private static Mat matC;
public static Mat matmul(Mat matA, Mat matB) {
matC = new Mat(matA.getNRows(),matB.getNColumns());
return mul(matA,matB);
}
private static Mat mul(Mat matA,Mat matB) {
int numRowForThread;
int numRowA = matA.getNRows();
int startRow = 0;
Worker[] myWorker = new Worker[NUM_OF_THREAD];
for (int j = 0; j < NUM_OF_THREAD; j++) {
if (j<NUM_OF_THREAD-1){
numRowForThread = (numRowA / NUM_OF_THREAD);
} else {
numRowForThread = (numRowA / NUM_OF_THREAD) + (numRowA % NUM_OF_THREAD);
}
myWorker[j] = new Worker(startRow, startRow+numRowForThread,matA,matB);
myWorker[j].start();
startRow += numRowForThread;
}
for (Worker worker : myWorker) {
try {
worker.join();
} catch (InterruptedException e) {
}
}
return matC;
}
private static class Worker extends Thread {
private int startRow, stopRow;
private Mat matA, matB;
public Worker(int startRow, int stopRow, Mat matA, Mat matB) {
super();
this.startRow = startRow;
this.stopRow = stopRow;
this.matA = matA;
this.matB = matB;
}
@Override
public void run() {
for (int i = startRow; i < stopRow; i++) {
for (int j = 0; j < matB.getNColumns(); j++) {
double sum = 0;
for (int k = 0; k < matA.getNColumns(); k++) {
sum += matA.get(i, k) * matB.get(k, j);
}
matC.set(i, j, sum);
}
}
}
}
對於class Mat
,我使用了這個實現:
public class Mat {
private double[][] mat;
public Mat(int n, int m) {
mat = new double[n][m];
}
public void set(int i, int j, double v) {
mat[i][j] = v;
}
public double get(int i, int j) {
return mat[i][j];
}
public int getNRows() {
return mat.length;
}
public int getNColumns() {
return mat[0].length;
}
}
根據每個單元的線程在 Eclipse 中嘗試以下代碼。 它工作正常,您可以檢查它。
class ResMatrix{
static int[][] arrres = new int[2][2];
}
class Matrix{
int [][] arr = new int[2][2];
void setV(int v) {
//int tmp = v;
for(int i=0;i<2;i++) {
for(int j=0;j<2;j++) {
arr[i][j] = v;
v = v + 1;
}
}
}
int [][] getV(){
return arr;
}
}
class Mul extends Thread {
public int row;
public int col;
Matrix m;
Matrix m1;
Mul(int row,int col,Matrix m,Matrix m1){
this.row = row;
this.col = col;
this.m = m;
this.m1 = m1;
}
public void run() {
//System.out.println("Started Thread: "+Thread.currentThread().getName());
int tmp=0;
for(int i=0;i<2;i++) {
tmp = tmp + this.m.getV()[row][i] * this.m1.getV()[i][col];
}
ResMatrix.arrres[row][col] = tmp;
System.out.println("Started Thread END: "+Thread.currentThread().getName());
}
}
public class Test {
//static int[][] arrres =new int[2][2];
public static void main(String[]args) throws InterruptedException {
Matrix mm = new Matrix();
mm.setV(1);
Matrix mm1 = new Matrix();
mm1.setV(2);
for(int i=0;i<2;i++) {
for(int j=0;j<2;j++) {
Mul mul = new Mul(i,j,mm,mm1);
mul.start();
// mul.join();
}
}
for(int i=0;i<2;i++) {
for(int j=0;j<2;j++) {
System.out.println("VALUE: "+ResMatrix.arrres[i][j]);
}
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.