Maruf_Hasan

Matrix Using thread

Sep 28th, 2019
190
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 3.04 KB | None | 0 0
  1. import java.util.Scanner;
  2.  
  3. class MatrixProduct extends Thread {
  4. private int[][] A;
  5. private int[][] B;
  6. private int[][] C;
  7. private int rig,col;
  8. private int dim;
  9.  
  10. public MatrixProduct(int[][] A,int[][] B,int[][] C,int rig, int col,int dim_com)
  11. {
  12. this.A=A;
  13. this.B=B;
  14. this.C=C;
  15. this.rig=rig;
  16. this.col=col;
  17. this.dim=dim_com;
  18. }
  19.  
  20. public void run()
  21. {
  22. for(int i=0;i<dim;i++){
  23. C[rig][col]+=A[rig][i]*B[i][col];
  24. }
  25. System.out.println("Thread "+rig+","+col+" complete.");
  26. }
  27. }
  28.  
  29. public class MatrixMultiplication {
  30. public static void main(String[] args)
  31. {
  32. Scanner in=new Scanner(System.in);
  33.  
  34. System.out.print("Row of Matrix A: ");
  35. int rA=in.nextInt();
  36. System.out.print("Column of Matrix A: ");
  37. int cA=in.nextInt();
  38. System.out.print("Row of Matrix B: ");
  39. int rB=in.nextInt();
  40. System.out.print("Column of Matrix B: ");
  41. int cB=in.nextInt();
  42. System.out.println();
  43.  
  44. if(cA!=rB)
  45. {
  46. System.out.println("We can't do the matrix product!");
  47. System.exit(-1);
  48. }
  49. System.out.println("The matrix result from product will be "+rA+" x "+cB);
  50. System.out.println();
  51. int[][] A=new int[rA][cA];
  52. int[][] B=new int[rB][cB];
  53. int[][] C=new int[rA][cB];
  54. MatrixProduct[][] thrd= new MatrixProduct[rA][cB];
  55.  
  56. System.out.println("Insert A:");
  57. System.out.println();
  58. for(int i=0;i<rA;i++)
  59. {
  60. for(int j=0;j<cA;j++)
  61. {
  62. System.out.print(i+","+j+" = ");
  63. A[i][j]=in.nextInt();
  64. }
  65. }
  66. System.out.println();
  67. System.out.println("Insert B:");
  68. System.out.println();
  69. for(int i=0;i<rB;i++)
  70. {
  71. for(int j=0;j<cB;j++)
  72. {
  73. System.out.print(i+","+j+" = ");
  74. B[i][j]=in.nextInt();
  75. }
  76. }
  77. in.close();
  78. System.out.println();
  79.  
  80. for(int i=0;i<rA;i++)
  81. {
  82. for(int j=0;j<cB;j++)
  83. {
  84. thrd[i][j]=new MatrixProduct(A,B,C,i,j,cA);
  85. thrd[i][j].start();
  86. }
  87. }
  88.  
  89. for(int i=0;i<rA;i++)
  90. {
  91. for(int j=0;j<cB;j++)
  92. {
  93. try{
  94. thrd[i][j].join();
  95. }
  96. catch(InterruptedException e){}
  97. }
  98. }
  99.  
  100. System.out.println();
  101. System.out.println("Result");
  102. System.out.println();
  103. for(int i=0;i<rA;i++)
  104. {
  105. for(int j=0;j<cB;j++)
  106. {
  107. System.out.print(C[i][j]+" ");
  108. }
  109. System.out.println();
  110. }
  111. }
  112. }
Advertisement
Add Comment
Please, Sign In to add comment