Guest User

Untitled

a guest
Feb 22nd, 2017
219
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.91 KB | None | 0 0
  1. public class Elaborato {
  2.  
  3. /**
  4. * @param args the command line arguments
  5. */
  6. public static void main(String[] args) {
  7. int N=2;
  8. int M=3;
  9.  
  10. Monitor m = new Monitor(N,M);
  11.  
  12. Generator g = new Generator(m, M, N);
  13. g.start();
  14.  
  15. Avg[] avg = new Avg[N];
  16. for (int i=0; i<N; i++){
  17. avg[i]=new Avg(i, m, M);
  18. avg[i].start();
  19.  
  20.  
  21. }
  22. }
  23.  
  24. }
  25.  
  26. public class Generator extends Thread {
  27.  
  28. private Monitor m;
  29. int M,N;
  30.  
  31. public Generator(Monitor m, int M, int N) {
  32. this.m = m;
  33. this.M=M;
  34. this.N=N;
  35. }
  36.  
  37. public void run() {
  38. int i= 0;
  39. try {
  40. do {
  41. m.startWrite();
  42. //scrive sul db
  43. for (int j=i; j<i+M*N; j++)
  44. m.doWrite(j);
  45. i+=M*N;
  46. m.endWrite();
  47. Thread.sleep(500);
  48. } while (true);
  49. } catch (InterruptedException ie) {
  50. }
  51. }
  52.  
  53. }
  54.  
  55. public class Avg extends Thread {
  56.  
  57. private int id;
  58. private Monitor m;
  59. private int M;
  60.  
  61. public Avg(int id, Monitor m, int M) {
  62. this.id = id;
  63. this.m = m;
  64. this.M = M;
  65. }
  66.  
  67. @Override
  68. public void run() {
  69. try {
  70. do {
  71. m.startRead();
  72. //gestisce le medie
  73. float q = m.doRead(id);
  74. q = q / (float) M;
  75. System.out.println("Avg " + id + " : " + q);
  76. m.endRead();
  77. Thread.sleep(500);
  78. } while (true);
  79. } catch (InterruptedException ie) {
  80. }
  81. }
  82. }
  83.  
  84.  
  85. public class Monitor {
  86.  
  87. private int nReaders;
  88. private int nWriters;
  89. private int[] numbers;
  90. private int N;
  91.  
  92. public Monitor(int N, int M) {
  93. nReaders = 0;
  94. nWriters = 0;
  95. this.N=N;
  96. numbers = new int[N * M];
  97.  
  98. }
  99.  
  100. public synchronized void startRead() throws InterruptedException {
  101. while (nWriters > 0) {
  102. wait();
  103. }
  104. nReaders++;
  105. notifyAll();
  106. }
  107.  
  108. public synchronized void endRead() throws InterruptedException {
  109. nReaders--;
  110. notifyAll();
  111. }
  112.  
  113. public synchronized void startWrite() throws InterruptedException {
  114. while (nReaders > 0) {
  115. wait();
  116. }
  117. nWriters++;
  118. notifyAll();
  119. }
  120.  
  121. public synchronized void endWrite() {
  122. nWriters--;
  123. notifyAll();
  124. }
  125.  
  126. public void doWrite(int i){
  127. numbers[i%(numbers.length)]=i;
  128. }
  129.  
  130. public int doRead(int id){
  131. int sum=0;
  132. for(int i=0; i<numbers.length; i++)
  133. if (i%(N)==id)
  134. sum+=numbers[i];
  135. return sum;
  136. }
  137. }
Advertisement
Add Comment
Please, Sign In to add comment