Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class Elaborato {
- /**
- * @param args the command line arguments
- */
- public static void main(String[] args) {
- int N=2;
- int M=3;
- Monitor m = new Monitor(N,M);
- Generator g = new Generator(m, M, N);
- g.start();
- Avg[] avg = new Avg[N];
- for (int i=0; i<N; i++){
- avg[i]=new Avg(i, m, M);
- avg[i].start();
- }
- }
- }
- public class Generator extends Thread {
- private Monitor m;
- int M,N;
- public Generator(Monitor m, int M, int N) {
- this.m = m;
- this.M=M;
- this.N=N;
- }
- public void run() {
- int i= 0;
- try {
- do {
- m.startWrite();
- //scrive sul db
- for (int j=i; j<i+M*N; j++)
- m.doWrite(j);
- i+=M*N;
- m.endWrite();
- Thread.sleep(500);
- } while (true);
- } catch (InterruptedException ie) {
- }
- }
- }
- public class Avg extends Thread {
- private int id;
- private Monitor m;
- private int M;
- public Avg(int id, Monitor m, int M) {
- this.id = id;
- this.m = m;
- this.M = M;
- }
- @Override
- public void run() {
- try {
- do {
- m.startRead();
- //gestisce le medie
- float q = m.doRead(id);
- q = q / (float) M;
- System.out.println("Avg " + id + " : " + q);
- m.endRead();
- Thread.sleep(500);
- } while (true);
- } catch (InterruptedException ie) {
- }
- }
- }
- public class Monitor {
- private int nReaders;
- private int nWriters;
- private int[] numbers;
- private int N;
- public Monitor(int N, int M) {
- nReaders = 0;
- nWriters = 0;
- this.N=N;
- numbers = new int[N * M];
- }
- public synchronized void startRead() throws InterruptedException {
- while (nWriters > 0) {
- wait();
- }
- nReaders++;
- notifyAll();
- }
- public synchronized void endRead() throws InterruptedException {
- nReaders--;
- notifyAll();
- }
- public synchronized void startWrite() throws InterruptedException {
- while (nReaders > 0) {
- wait();
- }
- nWriters++;
- notifyAll();
- }
- public synchronized void endWrite() {
- nWriters--;
- notifyAll();
- }
- public void doWrite(int i){
- numbers[i%(numbers.length)]=i;
- }
- public int doRead(int id){
- int sum=0;
- for(int i=0; i<numbers.length; i++)
- if (i%(N)==id)
- sum+=numbers[i];
- return sum;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment