日期:2014-05-20 浏览次数:20693 次
package chuangsi_0510.thread.timer; //生产者消费者问题 public class TestPC { /** * @param args */ public static void main(String[] args) { Queue queue = new Queue(20) ; Producer p1 = new Producer(queue) ; Producer p2 = new Producer(queue) ; Producer p3 = new Producer(queue) ; Consumer c1 = new Consumer(queue) ; Consumer c2 = new Consumer(queue) ; Consumer c3 = new Consumer(queue) ; Consumer c4 = new Consumer(queue) ; Thread tp1 = new Thread(p1) ; Thread tp2 = new Thread(p2) ; Thread tp3 = new Thread(p3) ; Thread tc1 = new Thread(c1) ; Thread tc2 = new Thread(c1) ; Thread tc3 = new Thread(c1) ; Thread tc4 = new Thread(c1) ; tp1.start() ; tp2.start() ; tp3.start() ; tc1.start() ; tc2.start() ; tc3.start() ; tc4.start() ; } } class Item { int id ; String name; public Item(int id , String name ) { this.id = id ; this.name = name ; } } class Queue { public Object[] items ; private int capacity ; private int in ; //下一个可以放商品的位置 private int out ;//下一个可以取商品的位置 private int size ; public Queue(int capacity) { this.capacity = capacity ; items = new Object[capacity] ; size = 0 ; in = out = 0 ; } public synchronized void insert(Object item) { while (size == capacity) { System.out.println("等待消费者把商品消费掉!"); try { this.wait() ; } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } this.notify() ; items[in] = item ; in = (in+1) % capacity ; size++ ; } public synchronized Object remove() { while (size == 0 ) { System.out.println("等待生产者生产产品!"); try { this.wait() ; } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } this.notify() ; Object o = items[out] ; out = (out + 1) % capacity ; size-- ; return o ; } } class Producer implements Runnable { private Queue queue ; public Producer(Queue queue) { this.queue = queue ; } public void run() { for (int i = 0 ; i < 30 ; i++ ) { Item item = new Item(i,Thread.currentThread().getName() + "生产的商品" +i) ; queue.insert(item) ; try { Thread.sleep(50) ; } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } class Consumer implements Runnable { private Queue queue ; public Consumer(Queue queue) { this.queue = queue ; } public void run() { for (int i = 0 ; i < 30 ; i++ ) { Item item = (Item)queue.remove() ; try { Thread.sleep( 20) ; } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println(Thread.currentThread().getName() + "消费了" + item.name) ; } } }