TD1: Add proper locking to the producer/consumer exo3 code.
[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 wait();
36 }
37 catch (InterruptedException e) {}
38 }
39 nbObj++;
40 tampon[prem] = obj;
41 prem = (prem + 1) % taille;
42 notify();
43 System.out.println(Thread.currentThread().getName() + " a depose " + (Integer)obj);
44 }
45
46
47 public synchronized Object preleve() {
48 while(isEmpty()) {
49 try {
50 wait();
51 }
52 catch (InterruptedException e) {}
53 }
54 Object outObj = null;
55 nbObj--;
56 outObj = tampon[der];
57 der = (der + 1) % taille;
58 notify();
59 System.out.println(Thread.currentThread().getName() + " a preleve " + (Integer)outObj);
60 return outObj;
61 }
62
63 } // fin class BufferCirc