Two N -order square matrix A and B phase multiplication procedures with java, and the result is stored in square matrix C.Among them, use the Runnable interface to implement the matrix multiplication
The initial values of。
Fang Array A and B are as follows: (two threads at the same time)
Output: the sum of all elements in C, the execution time of the program
The specific program is as follows:
package com.xing.matrix;
/**
*
* @Author yinxing
*
*/
public class matrixmul {
Public Static Void Main (String [] args) Throws InterruptedException {
// Todo Auto-Generatd Method Stub
int i, j, t = 0;
int leng = 1500;
Long Starttime, Endtime;
long a [] [] = new long [long] [length];
long b [] [] = new long [long] [length];
// -------------- to initialize matrix A and matrix B --------------
for (i = 0; I <lang; i ++)
{{
t = i+1;
for (j = 0; j <lang; j ++)
{{
a [i] [j] = t ++;
b [i] [j] = 1;
}
}
Matrix matrixone = new matrix (a, b, 0, length);
Matrix matrixtwo = New Matrix (a, B, 1, Leng);
Thread Threadone = New Thread (Matrixone);
Thread ThreadTwo = New Thread (MatrixTwo);
//-------------------Parallel Computing--------------------
starttime = System.currenttiMillis ();
threadone.start ();
threadtwo.start ();
threadone.Join ();
threadtwo.Join ();
endtime = System.currenttiMillis ();
System.out.println ("Parallel result =" + (matrixone.getsum () + matrixtwo.getsum ()););
System.out.println ("" parallel time = " + (endtime -starttime));
// --------------------------------------------------
starttime = System.currenttiMillis ();
Matrix matrixThree = New Matrix (a, B, 0, Leng);
matrixThree.serial ();
endtime = System.currenttiMillis ();
System.out.println ("serial result =" + matrixThree.getsum ());
System.out.println ("serial time =" + (endtime -starttime));
}
}
Class Matrix Implements Runnable {
Private long a [] [];
Private long b [] [];
Private long c [] [];
Private int Start;
Private int end;
Private Long Sum = 0;
public matrix (long a [] [], long b [] [], int, int en) {
this.a = a;
this.b = b;
this.start = ST;
this.end = en;
this.c = new long [en] [en];
}
@Override
public void run () {
// Todo Auto-Generatd Method Stub
int i, j, k;
for (i = start; i <end; i += 2)
{{
for (J = 0; J <END; J ++)
{{
C [i] [j] = 0;
for (k = 0; k <end; k ++)
{{
C [i] [j]+= a [i] [k]*b [k] [j];
}
}
}
for (i = start; i <end; i+= 2)
for (J = 0; J <END; J ++)
sum += c [i] [j];
}
Public void server () {// serial calculation of a matrix multiplication and then seeking
int i, j, k;
for (i = 0; i <h; i ++)
{{
for (J = 0; J <END; J ++)
{{
C [i] [j] = 0;
for (k = 0; k <end; k ++)
{{
C [i] [j]+= a [i] [k]*b [k] [j];
}
}
}
for (i = 0; i <h; i ++)
for (J = 0; J <END; J ++)
sum += c [i] [j];
}
public long getsum () {
Return this.sum;
}
}
Run results as follows:(Among them, the use of multi -nuclear combined parts is multiplication and demand)
relative acceleration ratio is: 58692/32020 = 1.832979387882573