Advertisement
PaweU

java lab12

Jan 14th, 2020
118
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.79 KB | None | 0 0
  1. import java.util.Locale;
  2. import java.util.concurrent.ArrayBlockingQueue;
  3. import java.util.concurrent.BlockingQueue;
  4.  
  5. public class Mean {
  6. static double[] array;
  7. static BlockingQueue<Double> results = new ArrayBlockingQueue<Double>(1000);
  8.  
  9. static void initArray(int size){
  10. array = new double[size];
  11. for(int i=0;i<size;i++){
  12. array[i]= Math.random()*size/(i+1);
  13. }
  14. }
  15.  
  16. static class MeanCalc extends Thread{
  17. private final int start;
  18. private final int end;
  19. double mean = 0;
  20.  
  21. MeanCalc(int start, int end){
  22. this.start = start;
  23. this.end = end;
  24. }
  25. public void run(){
  26. for(int i = start; i < end; i++) mean += array[i];
  27. mean /= (end-start);
  28. try {
  29. results.put(mean);
  30. } catch (InterruptedException e) {
  31. e.printStackTrace();
  32. }
  33. // System.out.printf(Locale.US,"%d-%d mean=%f\n",start,end,mean);
  34. }
  35. }
  36.  
  37. /**
  38. * Oblicza średnią wartości elementów tablicy array uruchamiając równolegle działające wątki.
  39. * Wypisuje czasy operacji
  40. * @param cnt - liczba wątków
  41. */
  42. static void parallelMean(int cnt) throws InterruptedException {
  43. // utwórz tablicę wątków
  44. MeanCalc threads[]=new MeanCalc[cnt];
  45. // utwórz wątki, podziel tablice na równe bloki i przekaż indeksy do wątków
  46. // załóż, że array.length dzieli się przez cnt)
  47. int threadSize = (int) array.length/cnt;
  48. for(int i = 0; i < cnt; i++) {
  49. threads[i] = new MeanCalc(i*threadSize, (i+1)*threadSize);
  50. }
  51.  
  52. double t1 = System.nanoTime()/1e6;
  53. //uruchom wątki
  54. for(MeanCalc mc:threads) mc.run();
  55.  
  56. double t2 = System.nanoTime()/1e6;
  57. // czekaj na ich zakończenie używając metody ''join''
  58. // for(MeanCalc mc:threads) {
  59. // mc.join();
  60. // }
  61. // oblicz średnią ze średnich v1
  62. // double mean = 0;
  63. // for(MeanCalc mc:threads) mean += mc.mean;
  64. // mean /= cnt;
  65.  
  66. // oblicz średnią ze średnich v2
  67. double mean = 0;
  68. for(int i = 0; i < cnt; i++) mean += results.take();
  69. mean /= cnt;
  70.  
  71. double t3 = System.nanoTime()/1e6;
  72. System.out.printf(Locale.US,"size = %d cnt=%d > t2-t1=%f t3-t1=%f mean=%f\n",
  73. array.length,
  74. cnt,
  75. t2-t1,
  76. t3-t1,
  77. mean);
  78. }
  79.  
  80. public static void main(String[] args) throws InterruptedException {
  81. initArray(128_000_000);
  82. // parallelMean(50);
  83. for(int cnt:new int[]{1,2,4,8,16,32,64,128}){
  84. parallelMean(cnt);
  85. }
  86. }
  87.  
  88.  
  89. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement