From 1180d8d3a4842901b6fb6fdae975fe5d39fe4039 Mon Sep 17 00:00:00 2001 From: =?utf8?q?J=C3=A9r=C3=B4me=20Benoit?= Date: Wed, 7 Mar 2018 20:34:07 +0100 Subject: [PATCH] TD1: Add proper locking to the producer/consumer exo3 code. MIME-Version: 1.0 Content-Type: text/plain; charset=utf8 Content-Transfer-Encoding: 8bit Signed-off-by: Jérôme Benoit --- TD1/exo3/BufferCirc.java | 36 +++++++++++++++++++++--------------- 1 file changed, 21 insertions(+), 15 deletions(-) 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; } -- 2.34.1