buffer-java
This is an old revision of the document!
Bounded buffer in Java
The class Buffer can be implemented as follows.
/** This class represents a bounded buffer. @author Franck van Breugel */ public class Buffer { private static final int SIZE = 10; private Object[] buffer; private int inCount; private int outCount; /** Creates an empty buffer. */ public Buffer() { this.buffer = new Object[Buffer.SIZE]; this.inCount = 0; this.outCount = 0; } /** Puts the given element in this buffer. @param element the element to be added. */ public void put(Object element) { while (this.inCount - this.outCount >= Buffer.SIZE) { this.wait(); } this.buffer[this.inCount % Buffer.SIZE] = element; this.inCount++; this.notifyAll(); } /** Removes an element from the buffer and returns it. @return an element of the buffer. */ public Object get() { while (this.incount - this.outCount <=0) { this.wait(); } Object temp = this.buffer[this.outCount % Buffer.SIZE]; this.outCount++; this.notifyAll(); return temp; } }
The class Consumer can be implemented as follows.
/** This class represents a consumer. @author Franck van Breugel */ public class Consumer extends Thread { private Buffer buffer; /** Creates a consumer for the given buffer. @param buffer the buffer from which the consumer consumes. */ public Consumer(Buffer buffer) { this.buffer = buffer; } /** */ public void run() { final int MILIS_IN_SEC = 1000; final int ITERATION = 20; for (int i = 0; i < ITERATION; i++) { System.out.println((Integer) buffer.get()); try { Thread.sleep((long) Math.random() * MILIS_IN_SEC); } catch (InterruptedException e){} } } }
buffer-java.1191500586.txt.gz · Last modified: 2007/10/04 12:23 by franck