1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
| /**
* This method will calculate the multiplication between two matrix of the same size
* and return the result in a new matrix
* @param Matrix m
* @return Matrix res
* @throws Exception
*/
public Matrix multiply(Matrix m) throws Exception{
double[][] table = new double[this.getNumberOfLines()][this.getNumberOfColumns()];
Matrix res = new Matrix(table);
long value = 0;
for (int k=0; k < this.getNumberOfColumns(); k++){
for (int i=1; i < this.getNumberOfLines()+1; i++){
for (int j=0; j < this.getNumberOfColumns(); j++)
value += this.matrix[i-1][j]*m.matrix[j][k];
res.matrix[i-1][k] = value;
value = 0;
}
}
return res;
}
/**
* Make a multiply operation between two matrix. This method is THREADED with a pool of fixed thread.
* When you call this method, the second parameter is the number of thread that you want to use.
* @param Matrix m
* @param int nbOfThread
*/
ExecutorService pool = Executors.newFixedThreadPool(5);
public Matrix threadedMultiply(Matrix m, int nbOfThread) throws InterruptedException{
double[][] table = new double[this.getNumberOfLines()][this.getNumberOfColumns()];
Matrix res = new Matrix(table);
long value = 0;
for (int k=0; k < this.getNumberOfColumns(); k++){
pool.execute(new ColumnMultiplication(this,table,res,k));
}
pool.shutdown();
while(true){
if (pool.awaitTermination(60,TimeUnit.SECONDS))
return res;
}
}
/**
* Make a multiply operation between two matrix. This method is THREADED with a pool of cached threads.
* @param Matrix m
*/
ExecutorService pool2 = Executors.newCachedThreadPool();
public Matrix threadedMultiply(Matrix m) throws InterruptedException{
double[][] table = new double[this.getNumberOfLines()][this.getNumberOfColumns()];
Matrix res = new Matrix(table);
long value = 0;
for (int k=0; k < this.getNumberOfColumns(); k++){
pool2.execute(new ColumnMultiplication(this,table,res,k));
}
pool2.shutdown();
while(true){
if (pool2.awaitTermination(60,TimeUnit.SECONDS))
return res;
}
}
/**
*
* @author Cyrill Gremaud
* This internal private class is only here for the treaded multiply method.
* It implements Runnable interface to manage the threads
*/
private class ColumnMultiplication implements Runnable{
private Matrix matrix, res;
private double[][] table;
private int k;
public ColumnMultiplication(Matrix matrix, double[][] table, Matrix res, int k) {
this.k = k;
this.matrix = matrix;
this.res = res;
this.table = table;
}
@Override
public void run() {
double value = 0;
for (int i=1; i < matrix.getNumberOfLines()+1; i++){
for (int j=0; j < matrix.getNumberOfColumns(); j++)
value += matrix.matrix[i-1][j]*table[j][k];
res.matrix[i-1][k] = value;
value = 0;
}
}
} |