Advertisement
Guest User

Untitled

a guest
Feb 21st, 2019
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.64 KB | None | 0 0
  1. import java.lang.Thread;
  2. import java.util.Random;
  3.  
  4. public class ThreadedMatrices
  5. {
  6.  
  7.     public ThreadedMatrices(int a_row, int a_col, int b_row, int b_col)
  8.     {
  9.         Random rand = new Random();
  10.         int[][] m1 = new int[a_row][a_col];
  11.         int[][] m2 = new int[b_row][b_col];
  12.         int[][] product;
  13.  
  14.         for (int i=0; i < m1.length; i++)
  15.         {
  16.             for (int j=0; j < m1[i].length; j++)
  17.                 m1[i][j] = rand.nextInt(10);
  18.         }
  19.         for (int i=0; i < m2.length; i++)
  20.         {
  21.             for (int j=0; j < m2[i].length; j++)
  22.                 m2[i][j] = rand.nextInt(10);
  23.         }
  24.        
  25.         product = multiply(m1, m2);
  26.         display(product);
  27.     }
  28.  
  29.     public static void main(String[] args)
  30.     {
  31.         new ThreadedMatrices(2,3, 3,4);
  32.     }
  33.  
  34.     public int[][] multiply(int[][] m1, int[][] m2)
  35.     {
  36.         int[][] matrix = new int[m1.length][m2[0].length];
  37.  
  38.         for (int i=0; i < m1.length; i++)
  39.         {
  40.             for (int j=0; j < m2[0].length; j++)
  41.             {
  42.                 int x;
  43.  
  44.                 Calculation calc = new Calculation(m1, m2, i, j);
  45.                 calc.start();
  46.                 x = calc.getValue();
  47.  
  48.                 matrix[i][j] = x;
  49.             }
  50.         }
  51.  
  52.         return matrix;
  53.     }
  54.  
  55.     public void display(int[][] product)
  56.     {
  57.          for (int i=0; i < product.length; i++)
  58.         {
  59.             for (int j=0; j < product[0].length; j++)
  60.                 System.out.print(product[i][j] + "  ");
  61.             System.out.println();
  62.         }
  63.     }
  64.  
  65.     private class Calculation extends Thread
  66.     {
  67.         int[][] a;
  68.         int[][] b;
  69.         int i, j;
  70.         int x;
  71.  
  72.         public Calculation(int[][] a, int[][] b, int i, int j)
  73.         {
  74.             this.a = a;
  75.             this.b = b;
  76.             this.i = i;
  77.             this.j = j;
  78.         }
  79.  
  80.         public void run()
  81.         {
  82.             for (int h=0; h < b.length; h++)
  83.                 x = x + (a[i][h] * b[h][j]);
  84.         }
  85.  
  86.         public int getValue()
  87.         {
  88.             return x;
  89.         }
  90.     }
  91.  
  92. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement