public class BoundedBuffer { public BoundedBuffer() { // buffer is initially empty count = 0; in = 0; out = 0; buffer = new Object[BUFFER_SIZE]; } // producer and consumer will call this to nap public static void napping(int t) { int sleepTime = (int) (t * Math.random() ); try { Thread.sleep(sleepTime * 1000); } catch(InterruptedException e) { System.out.println(e); } } public void enter(Object item) { int temp; while (count >= BUFFER_SIZE) Thread.yield(); // add item to the buffer: // Increment count temp = count; Thread.yield(); temp = temp + 1; count = temp; // Put item in open space in buffer buffer[in] = item; in = (in + 1) % BUFFER_SIZE; // circular buffer System.out.println(Thread.currentThread().getName() + " entered " + item + " (count = " + count + ")"); } public Object remove() { int temp; Object item; while (count == 0) Thread.yield(); // remove an item to the buffer: // Decrement count temp = count; Thread.yield(); temp = temp - 1; count = temp; // Remove item from next buffer location item = buffer[out]; out = (out + 1) % BUFFER_SIZE; // circular buffer System.out.println("\t\t\t\t" + Thread.currentThread().getName() + " consumed " + item + " (count = " + count + ")"); return item; } private static final int BUFFER_SIZE = 3; private int count, in, out; private Object[] buffer; }