... shared by producer and consumer threads
17      private boolean occupied = false; // whether buffer is occupied
18
19      // place int value into buffer
20      @Override
21      public void blockingPut(int value) throws InterruptedException {
22         accessLock.lock(); // lock this object
23
24         // output thread information and buffer information, then wait
25         try {
26            // while buffer is not empty, place thread in waiting state
27            while (occupied) {
28               System.out.println("Producer tries to write.");
29               displayState("Buffer full. Producer waits.");
30               canWrite.await(); // wait until buffer is empty
31            }
32
33            buffer = value; // set new buffer value
34
35            // indicate producer cannot store another value
36            // until consumer retrieves current buffer value
37            occupied = true;  ...

Get Java How To Program, Late Objects, 11th Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.