Advertisement
Guest User

Untitled

a guest
Mar 30th, 2015
221
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.63 KB | None | 0 0
  1. public class ParallelMatrix {
  2.  
  3. public final static int N = 1000; //Random size of matrix
  4.  
  5. public static void main(String[] args) throws InterruptedException {
  6.  
  7. long startTime = System.currentTimeMillis();
  8.  
  9.  
  10. //Create and multiply matrix of random size N.
  11. double [][] a = new double [N][N];
  12. double [][] b = new double [N][N];
  13. double [][] c = new double [N][N];
  14.  
  15. int i,j,k;
  16.  
  17.  
  18. for(i = 0; i < N ; i++)
  19. for(j = 0; j < N ; j++){
  20. a[i][j] = i + j;
  21. b[i][j] = i * j;
  22. }
  23. //newFixedThreadPool(1)
  24. ExecutorService pool = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
  25. for(i = 0; i < N; i++) {
  26. for(j = 0; j < N; j++) {
  27. pool.submit(new Multi(N,i,j,a,b,c));
  28.  
  29.  
  30. }
  31. }
  32. pool.shutdown();
  33. pool.awaitTermination(1, TimeUnit.DAYS);
  34. long endTime = System.currentTimeMillis();
  35. System.out.println("Calculation completed in " +
  36. (endTime - startTime) + " milliseconds");
  37.  
  38. }
  39. static class Multi implements Runnable {
  40. final int N;
  41. final double [][] a;
  42. final double [][] b;
  43. final double [][] c;
  44. final int i;
  45. final int j;
  46.  
  47. public Multi(int N, int i, int j, double[][] a, double[][] b, double[][] c){
  48. this.N=N;
  49. this.i=i;
  50. this.j=j;
  51. this.a=a;
  52. this.b=b;
  53. this.c=c;
  54. }
  55.  
  56.  
  57. @Override
  58. public void run() {
  59. for(int k = 0; k < N; k++) c[i][j] += a[i][k] * b[k][j];
  60. }
  61.  
  62. }
  63.  
  64. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement