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