buffer-java
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 synchronized 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 synchronized 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) { super(); this.buffer = buffer; } /** Gets 20 elements from the buffer and prints them. */ public void run() { final int MILIS_IN_SEC = 1000; final int ITERATION = 20; for (int i = 0; i < ITERATION; i++) { System.out.println((Integer) this.buffer.get()); try { Thread.sleep((long) Math.random() * MILIS_IN_SEC); } catch (InterruptedException e){} } } }
The class Producer can be implemented as follows.
/** This class represents a producer. @author Franck van Breugel */ public class Producer extends Thread { private Buffer buffer; /** Creates a producer for the given buffer. @param buffer the buffer from which the producer produces. */ public Producer(Buffer buffer) { super(); this.buffer = buffer; } /** */ public void run() { final int MILIS_IN_SEC = 1000; final int ITERATION = 20; for (int i = 0; i < ITERATION; i++) { this.buffer.put(new Integer(i)); try { Thread.sleep((long) Math.random() * MILIS_IN_SEC); } catch (InterruptedException e){} } } }
Finally, we give an app that puts everything together.
/** This app creates a buffer, a consumer and a producer. @author Franck van Breugel */ public class BufferTest { /** Creates a buffer, consumer and producer. */ public static void main(String[] args) { Buffer buffer = new Buffer(); Producer producer = new Producer(buffer); Consumer consumer = new Consumer(buffer); producer.start(); consumer.start(); } }
buffer-java.txt · Last modified: 2007/10/04 14:03 by franck