Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.lang.Thread;
- import java.util.Random;
- public class ThreadedMatrices
- {
- public ThreadedMatrices(int a_row, int a_col, int b_row, int b_col)
- {
- Random rand = new Random();
- int[][] m1 = new int[a_row][a_col];
- int[][] m2 = new int[b_row][b_col];
- int[][] product;
- for (int i=0; i < m1.length; i++)
- {
- for (int j=0; j < m1[i].length; j++)
- m1[i][j] = rand.nextInt(10);
- }
- for (int i=0; i < m2.length; i++)
- {
- for (int j=0; j < m2[i].length; j++)
- m2[i][j] = rand.nextInt(10);
- }
- product = multiply(m1, m2);
- display(product);
- }
- public static void main(String[] args)
- {
- new ThreadedMatrices(2,3, 3,4);
- }
- public int[][] multiply(int[][] m1, int[][] m2)
- {
- int[][] matrix = new int[m1.length][m2[0].length];
- for (int i=0; i < m1.length; i++)
- {
- for (int j=0; j < m2[0].length; j++)
- {
- int x;
- Calculation calc = new Calculation(m1, m2, i, j);
- calc.start();
- x = calc.getValue();
- matrix[i][j] = x;
- }
- }
- return matrix;
- }
- public void display(int[][] product)
- {
- for (int i=0; i < product.length; i++)
- {
- for (int j=0; j < product[0].length; j++)
- System.out.print(product[i][j] + " ");
- System.out.println();
- }
- }
- private class Calculation extends Thread
- {
- int[][] a;
- int[][] b;
- int i, j;
- int x;
- public Calculation(int[][] a, int[][] b, int i, int j)
- {
- this.a = a;
- this.b = b;
- this.i = i;
- this.j = j;
- }
- public void run()
- {
- for (int h=0; h < b.length; h++)
- x = x + (a[i][h] * b[h][j]);
- }
- public int getValue()
- {
- return x;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement