class BoundedBuffer { private int front = 0, back = 0, count = 0; private int NoOfElems; private int [] Elements; public BoundedBuffer( int size ) { NoOfElems = size; Elements = new int[NoOfElems]; } // BoundedBuffer public int query() { return count; } // query public synchronized void insert( int elem ) { while ( count == NoOfElems ) { try { wait(); } catch( InterruptedException ex ) { } // try } // while Elements[back] = elem; back = ( back + 1 ) % NoOfElems; count += 1; notify(); } // insert public synchronized int remove() { int elem; while ( count == 0 ) { try { wait(); } catch( InterruptedException ex ) { } // try } // while elem = Elements[front]; front = ( front + 1 ) % NoOfElems; count -= 1; notify(); return elem; } // remove } // BoundedBuffer class Consumer extends Thread { private BoundedBuffer buf; public Consumer( BoundedBuffer buf ) { this.buf = buf; } // Consumer public void run() { for ( ;; ) { int elem = buf.remove(); if ( elem == -1 ) break; System.out.println( "Consumer:" + this + " value:" + elem ); } // for } // run } // Consumer class Producer extends Thread { private BoundedBuffer buf; public Producer( BoundedBuffer buf ) { this.buf = buf; } // Producer public void run() { int NoOfElems = 40; for ( int i = 1; i <= NoOfElems; i += 1 ) { int elem = (int)(Math.random() * 100); System.out.println( "Producer:" + this + " value:" + elem ); buf.insert( elem ); } // for } // run } // Producer public class BB { public static void main( String[] args ) throws InterruptedException { int NoOfCons = 3, NoOfProds = 4, i; BoundedBuffer buf = new BoundedBuffer( 5 ); Consumer[] cons = new Consumer[NoOfCons]; Producer[] prods = new Producer[NoOfProds]; for ( i = 0; i < NoOfCons; i += 1 ) { cons[i] = new Consumer( buf ); cons[i].start(); } // for for ( i = 0; i < NoOfProds; i += 1 ) { prods[i] = new Producer( buf ); prods[i].start(); } // for for ( i = 0; i < NoOfProds; i += 1 ) { prods[i].join(); } // for for ( i = 0; i < NoOfCons; i += 1 ) { buf.insert( -1 ); } // for for ( i = 0; i < NoOfCons; i += 1 ) { cons[i].join(); } // for System.out.println( "successful completion" ); } // main } // BB