生产者与消费者模型中,要保证以下几点:
1 同一时间内只能有一个生产者生产
2 同一时间内只能有一个消费者消费
3 生产者生产的同时消费者不能消费
4 消息队列满时生产者不能继续生产
5 消息队列空时消费者不能继续消费
package ying.threadWait; import java.util.Vector; public class TestConsumer { public static void main(String[] args) { WareHouse warehouse = new WareHouse(0) ; Producer pro1 = new Producer(15 , warehouse) ; Consumer cust1 = new Consumer(30 , warehouse) ; Consumer cust2 = new Consumer(20 , warehouse) ; Consumer cust3 = new Consumer(15 , warehouse) ; pro1.start() ; cust1.start() ; cust2.start() ; cust3.start() ; System.out.println("Bye"); } } class WareHouse { public int cur_size ; public final static int max_size = 50 ; public WareHouse() { } public WareHouse(int size) { this.cur_size = size ; } public synchronized void produce(int produceNum) { while (produceNum + cur_size > max_size) { System.out.println("The quantity of product to produce is " + produceNum + " which is over the remaining storage limit : " + (max_size - cur_size)); try { System.out.println("Producer " + Thread.currentThread().getName() + " waits"); wait() ; } catch (InterruptedException e) { e.printStackTrace(); } } cur_size += produceNum ; System.out.println(Thread.currentThread().getName() + " has produced " + produceNum + " pieces of product."); notifyAll() ; } public synchronized void consume(int needNum) { while (needNum > cur_size) { try { System.out.println("Consumer " + Thread.currentThread().getName() + " waits"); wait() ; } catch (InterruptedException e) { e.printStackTrace(); } } cur_size -= needNum ; System.out.println("The customer has consumed " + needNum + " pieces of product."); notifyAll() ; } } class Producer extends Thread { private int produceNum ; private WareHouse warehouse ; Producer(int num , WareHouse house) { this.produceNum = num ; this.warehouse = house ; } public void run() { while (true) { warehouse.produce(produceNum) ; } } }
class Consumer extends Thread { private int needNum ; private WareHouse warehouse ; Consumer(int num , WareHouse warehouse) { this.needNum = num ; this.warehouse = warehouse ; } public void run() { warehouse.consume(needNum) ; } }
有空时可以参考:http://www.blogjava.net/amigoxie/archive/2007/04/11/110006.html