Commit | Line | Data |
---|---|---|
18eb400b JB |
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 | ||
38 | wait(); | |
39 | } | |
40 | catch (InterruptedException e) {} | |
41 | } | |
42 | nbObj++; | |
43 | tampon[prem] = obj; | |
44 | prem = (prem + 1) % taille; | |
45 | //System.out.println(Thread.currentThread().getName() + " a depose " + (Integer)obj); | |
46 | notifyAll(); | |
47 | } | |
48 | ||
49 | ||
50 | public synchronized Object preleve() { | |
51 | while(isEmpty()) { | |
52 | try { | |
53 | System.out.println("Buffer is empty: " + Thread.currentThread().getName() | |
54 | + " is waiting, size: " + nbObj); | |
55 | wait(); | |
56 | } | |
57 | catch (InterruptedException e) {} | |
58 | } | |
59 | Object outObj = null; | |
60 | nbObj--; | |
61 | outObj = tampon[der]; | |
62 | der = (der + 1) % taille; | |
63 | //System.out.println(Thread.currentThread().getName() + " a preleve " + (Integer)outObj); | |
64 | notifyAll(); | |
65 | return outObj; | |
66 | } | |
67 | ||
68 | } // fin class BufferCirc |