e03e8ea950e2cdd3ab244bde76454722f2abbd90
[TD_SR.git] / TD1 / exo3 / BufferCirc.java
1
2
3 /**
4 * implementation du producteur consommateur avec un buffer circulaire
5 */
6 public class BufferCirc {
7
8 private Object[] tampon;
9 private int taille;
10 private int prem, der, nbObj;
11
12
13 public BufferCirc (int t) {
14 taille = t;
15 tampon = new Object[taille];
16 prem = 0;
17 der = 0;
18 nbObj = 0;
19 }
20
21
22 public boolean isEmpty() {
23 return nbObj == 0;
24 }
25
26
27 public boolean isFull() {
28 return nbObj == taille;
29 }
30
31
32 public synchronized void depose(Object obj) {
33 while(isFull()) {
34 try {
35 System.out.println("Buffer is full: " + Thread.currentThread().getName()
36 + " is waiting, size: " + nbObj);
37 wait();
38 }
39 catch (InterruptedException e) {}
40 }
41 nbObj++;
42 tampon[prem] = obj;
43 prem = (prem + 1) % taille;
44 //System.out.println(Thread.currentThread().getName() + " a depose " + (Integer)obj);
45 notifyAll();
46 }
47
48
49 public synchronized Object preleve() {
50 while(isEmpty()) {
51 try {
52 System.out.println("Buffer is empty: " + Thread.currentThread().getName()
53 + " is waiting, size: " + nbObj);
54 wait();
55 }
56 catch (InterruptedException e) {}
57 }
58 Object outObj = null;
59 nbObj--;
60 outObj = tampon[der];
61 der = (der + 1) % taille;
62 //System.out.println(Thread.currentThread().getName() + " a preleve " + (Integer)outObj);
63 notifyAll();
64 return outObj;
65 }
66
67 } // fin class BufferCirc