TD1: Add proper locking to the producer/consumer exo3 code.
authorJérôme Benoit <jerome.benoit@piment-noir.org>
Wed, 7 Mar 2018 19:34:07 +0000 (20:34 +0100)
committerJérôme Benoit <jerome.benoit@piment-noir.org>
Wed, 7 Mar 2018 19:34:07 +0000 (20:34 +0100)
Signed-off-by: Jérôme Benoit <jerome.benoit@piment-noir.org>
TD1/exo3/BufferCirc.java

index 71204cc158c1680631d02c0714d338e90f9785a1..335420aa60e278d80fb5ef6aa64078a7264fff1c 100644 (file)
@@ -30,27 +30,33 @@ public class BufferCirc {
 \r
 \r
        public synchronized void depose(Object obj) {\r
-               if (!isFull()) {\r
-                       nbObj++;\r
-                       tampon[prem] = obj;\r
-                       prem = (prem + 1) % taille;\r
-                       System.out.println(Thread.currentThread().getName() + " a depose " + (Integer)obj);\r
-               } else {\r
-                       System.out.println("Buffer plein pour " + Thread.currentThread().getName());\r
+               while(isFull()) {\r
+                       try {\r
+                               wait();\r
+                       }\r
+                       catch (InterruptedException e) {}\r
                }\r
+               nbObj++;\r
+               tampon[prem] = obj;\r
+               prem = (prem + 1) % taille;\r
+               notify();\r
+               System.out.println(Thread.currentThread().getName() + " a depose " + (Integer)obj);\r
        }\r
 \r
 \r
        public synchronized Object preleve() {\r
-               Object outObj = null;\r
-               if (isEmpty()) {\r
-                       nbObj--;\r
-                       outObj = tampon[der];\r
-                       der = (der + 1) % taille;\r
-                       System.out.println(Thread.currentThread().getName() + " a preleve " + (Integer)outObj);\r
-               } else {\r
-                       System.out.println("Buffer vide pour " + Thread.currentThread().getName());\r
+               while(isEmpty()) {\r
+                       try {\r
+                               wait();\r
+                       }\r
+                       catch (InterruptedException e) {}\r
                }\r
+               Object outObj = null;\r
+               nbObj--;\r
+               outObj = tampon[der];\r
+               der = (der + 1) % taille;\r
+               notify();\r
+               System.out.println(Thread.currentThread().getName() + " a preleve " + (Integer)outObj);\r
                return outObj;\r
        }\r
 \r