Advertisement
Guest User

Untitled

a guest
Jan 20th, 2019
55
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.68 KB | None | 0 0
  1. package lista11.zad3;
  2.  
  3. public class BoundedBuffer implements Produce, Consume {
  4.     final private int N;
  5.     private int in = 0, out = 0, n = 0;
  6.     private int[] elems;
  7.  
  8.     public BoundedBuffer(int N) {
  9.         this.N = N; elems = new int[N];
  10.     }
  11.  
  12.     public synchronized void showBuf(){
  13.         for(int e: elems) System.out.print(e+" ");
  14.         System.out.println();
  15.     }
  16.  
  17.     public synchronized void put(int x) {
  18.         while (n >= N) // n : <0 ; N>    while(Buffer pełny)
  19.           try {
  20.               System.out.println(Thread.currentThread().getName()+" waiting with " + x);
  21.               wait();
  22.           } catch (InterruptedException e) {System.out.println(e);}
  23.  
  24.         elems[in] = x; in = (in + 1) % N ; n += 1; // dodaj do bufera x, zwieksz indeks dla kolejnego elementu, zwieksz licznik
  25.  
  26.         System.out.println(Thread.currentThread().getName()+" produced: " + x);
  27.         showBuf();
  28.         if (n == 1){
  29.             notify();
  30.             System.out.println("Put notify");//jesli jest jeden element to wywolaj notify,, jesli zlikwidujemy ifa i damy notify bezwarunkowo to rozwiazemy problem
  31.         }
  32.     }
  33.  
  34.     public synchronized int take() {
  35.         while (n == 0)
  36.           try {
  37.               System.out.println(Thread.currentThread().getName()+" waiting");
  38.               wait();
  39.           } catch (InterruptedException e) {System.out.println(e);}
  40.         int x = elems[out];elems[out] = -1; out = (out + 1) % N ; n -= 1;
  41.         System.out.println(Thread.currentThread().getName()+" consuming: " + x);
  42.         showBuf();
  43.         if (n == N-1){
  44.             notify();
  45.             System.out.println("Take notify");
  46.         }
  47.         return x;
  48.     }
  49. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement