日期:2014-05-20 浏览次数:20769 次
import java.util.ArrayList; import java.util.List; import java.util.Queue; import java.util.concurrent.LinkedBlockingQueue; public class Producer { private final Queue<String> productQueue = new LinkedBlockingQueue<String> (); private final List<Consumer> consumers = new ArrayList<Consumer> (); public void addConsumer(Consumer c) { this.consumers.add(c); } public void notifyProductGenerated() { for(Consumer c : this.consumers) { c.notifyProductGenerated(); } } public static void main(String... args) { Producer producer = new Producer(); final Consumer consumer = new Consumer(producer.productQueue); producer.addConsumer(consumer); new Thread(new Runnable() { @Override public void run() { consumer.consume(); } }).start(); for(int i = 0; i < 100; i++) { try { Thread.sleep(1000 * 1); } catch(InterruptedException ex) { ex.printStackTrace(); } producer.productQueue.add("" + i); System.out.println("" + i + " made."); producer.notifyProductGenerated(); } } } class Consumer { private Queue<String> productQueue; public Consumer(Queue<String> productQueue) { this.productQueue = productQueue; } public synchronized void notifyProductGenerated() { notifyAll(); } public synchronized void consume() { String product = null; while(true) { product = productQueue.poll(); if(product == null) { try { wait(); continue; } catch (InterruptedException ex) { ex.printStackTrace(); return; } } try { Thread.sleep(1000 * 10); } catch(InterruptedException ex) { ex.printStackTrace(); return; } System.out.println("run out of product " + product); } } }