From: Jérôme Benoit Date: Wed, 7 Mar 2018 19:34:07 +0000 (+0100) Subject: TD1: Add proper locking to the producer/consumer exo3 code. X-Git-Url: https://git.piment-noir.org/?a=commitdiff_plain;h=1180d8d3a4842901b6fb6fdae975fe5d39fe4039;p=TD_SR.git TD1: Add proper locking to the producer/consumer exo3 code. Signed-off-by: Jérôme Benoit --- diff --git a/TD1/exo3/BufferCirc.java b/TD1/exo3/BufferCirc.java index 71204cc..335420a 100644 --- a/TD1/exo3/BufferCirc.java +++ b/TD1/exo3/BufferCirc.java @@ -30,27 +30,33 @@ public class BufferCirc { public synchronized void depose(Object obj) { - if (!isFull()) { - nbObj++; - tampon[prem] = obj; - prem = (prem + 1) % taille; - System.out.println(Thread.currentThread().getName() + " a depose " + (Integer)obj); - } else { - System.out.println("Buffer plein pour " + Thread.currentThread().getName()); + while(isFull()) { + try { + wait(); + } + catch (InterruptedException e) {} } + nbObj++; + tampon[prem] = obj; + prem = (prem + 1) % taille; + notify(); + System.out.println(Thread.currentThread().getName() + " a depose " + (Integer)obj); } public synchronized Object preleve() { - Object outObj = null; - if (isEmpty()) { - nbObj--; - outObj = tampon[der]; - der = (der + 1) % taille; - System.out.println(Thread.currentThread().getName() + " a preleve " + (Integer)outObj); - } else { - System.out.println("Buffer vide pour " + Thread.currentThread().getName()); + while(isEmpty()) { + try { + wait(); + } + catch (InterruptedException e) {} } + Object outObj = null; + nbObj--; + outObj = tampon[der]; + der = (der + 1) % taille; + notify(); + System.out.println(Thread.currentThread().getName() + " a preleve " + (Integer)outObj); return outObj; }