Commit 5a9aff78 authored by Mikhail.Barash's avatar Mikhail.Barash
Browse files

initial commit

parents
package Task1;
import java.util.*;
public class Main {
// random matrices
public static double[][] generate(int rows, int columns) {
double[][] ret = new double[rows][columns];
Random random = new Random();
for (int i = 0; i < rows; i++)
for (int j = 0; j < columns; j++)
ret[i][j] = random.nextDouble() * 10;
return ret;
}
public static void main(String[] args) {
final int size = 1000;
double[][] matrix1 = generate(size, size);
double[][] matrix2 = generate(size, size);
double[][] result = new double[matrix1.length][matrix2[0].length];
System.out.println("Serial version running...");
Date start = new Date();
SerialMult.multiply(matrix1, matrix2, result);
Date end = new Date();
System.out.println("Serial Multiplication: " + (end.getTime() - start.getTime()) + "ms");
System.out.println("Parallel version by row running...");
start = new Date();
MatrixMult.multiply(matrix1, matrix2, result);
end = new Date();
System.out.println("Parallel Row: "+ (end.getTime() - start.getTime()) + "ms");
}
}
package Task1;
import java.util.*;
public class MatrixMult {
public static void multiply(double[][] A, double[][] B, double[][] C) {
List<Thread> threads = new ArrayList<>();
for (int i = 0; i < A.length; i++) {
RowMultiplierTask task = new RowMultiplierTask(C, A, B, i);
Thread thread = new Thread(task);
// TODO: your solution here
if (threads.size() % 10 == 0) { waitForThreads(threads); }
}
if (!threads.isEmpty()) { waitForThreads(threads); }
}
private static void waitForThreads(List<Thread> threads) {
for (Thread thread : threads) {
try {
// TODO: your solution here
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
threads.clear();
}
}
package Task1;
public class RowMultiplierTask implements Runnable {
private final double[][] C, A, B;
private final int row;
public RowMultiplierTask(double[][] C, double[][] A, double[][] B, int i) {
this.C = C;
this.A = A;
this.B = B;
this.row = i;
}
public void run() {
for (int j = 0; j < B[0].length; j++) {
C[row][j] = 0;
for (int k = 0; k < A[row].length; k++)
C[row][j] += A[row][k] * B[k][j];
} // for j
}
}
package Task1;
public class SerialMult {
public static void multiply(double[][] A, double[][] B, double[][] C) {
int m = A.length;
int n = A[0].length;
int k = B[0].length;
for (int I = 0; I < m; I++)
for (int J = 0; J < k; J++) {
C[I][J] = 0;
for (int K = 0; K < n; K++)
C[I][J] += A[I][K] * B[K][J];
} // for J
}
}
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment