package examples; import java.util.*; /* * @author Kenneth J. Goldman, Washington University, kjg@wustl.edu * Created: Feb 22, 2005 * */ public class BlockingQueue { private LinkedList queue; int capacity; public BlockingQueue(int capacity) { this.capacity = capacity; queue = new LinkedList(); } public synchronized void enqueue(E x) { while (queue.size() >= capacity) try { System.out.println("waiting to enqueue " + x); wait(); } catch (InterruptedException e) { // Do nothing. Just go check the queue again. } queue.addLast(x); notifyAll(); } public synchronized E dequeue() { while (queue.isEmpty()) try { System.out.println("waiting to dequeue"); wait(); } catch (InterruptedException e) { // Do nothing. Just go check the queue again. } E x = queue.removeFirst(); notifyAll(); return x; } public static void main(String[] args) { final BlockingQueue q = new BlockingQueue(3); class Producer extends Thread { int base; Producer(int base) { this.base = base; } public void run() { int i = 0; while (i <= 50) q.enqueue(base + i++); } } class Consumer extends Thread { public void run() { int i = 0; while (true) { System.out.println("got " + (i = q.dequeue())); } } } Thread producer = new Producer(0); Thread producer2 = new Producer(100); Thread consumer = new Consumer(); producer.start(); producer2.start(); consumer.start(); } } /* SAMPLE OUTPUT WITH ONE CONSUMER AND ONE PRODUCER: waiting to dequeue waiting to enqueue 3 got 0 got 1 got 2 waiting to dequeue waiting to enqueue 6 got 3 got 4 got 5 waiting to dequeue waiting to enqueue 9 got 6 got 7 got 8 waiting to dequeue waiting to enqueue 12 got 9 got 10 got 11 waiting to dequeue waiting to enqueue 15 got 12 got 13 got 14 waiting to dequeue waiting to enqueue 18 got 15 got 16 got 17 waiting to dequeue waiting to enqueue 21 got 18 got 19 got 20 waiting to dequeue waiting to enqueue 24 got 21 got 22 got 23 waiting to dequeue waiting to enqueue 27 got 24 got 25 got 26 waiting to dequeue waiting to enqueue 30 got 27 got 28 got 29 waiting to dequeue waiting to enqueue 33 got 30 got 31 got 32 waiting to dequeue waiting to enqueue 36 got 33 got 34 got 35 waiting to dequeue waiting to enqueue 39 got 36 got 37 got 38 waiting to dequeue waiting to enqueue 42 got 39 got 40 got 41 waiting to dequeue waiting to enqueue 45 got 42 got 43 got 44 waiting to dequeue waiting to enqueue 48 got 45 got 46 got 47 waiting to dequeue got 48 got 49 got 50 */