public class Depot { int capacity ; int size; public Depot(int capacity){ this.capacity = capacity; this.size = 0; } public synchronized void produce(int val){ try{ int left = val;//val可能 > capacity,因此需要多次生产 while(left > 0){// while(size >= capacity){//当库存已满时,生产者需要将自己挂起,并唤醒消费者,让消费者来消费。 wait(); } int inc = (size + left) > capacity ? (capacity - size) : left;//每次生产的数量与capacity有关 size += inc; left -= inc; System.out.printf("%s produce(%3d) --> left=%3d, inc=%3d, size=%3d ", Thread.currentThread().getName(), val, left, inc, size); notifyAll();//唤醒消费者来消费 } }catch(Exception e){ } } public synchronized void consum(int val){ try{ int left = val; while(left > 0){ while(size <= 0){//当库存为0时,消费者将自己挂起,通知生产者生产 wait(); } int dec = (size > left) ? left : size;//同上 size -= dec; left -= dec; System.out.printf("%s consume(%3d) --> left=%3d, dec=%3d, size=%3d ", Thread.currentThread().getName(), val, left, dec, size); notifyAll(); } }catch(Exception e){} } }
生产者& 消费者对工厂的访问:
public class ConsumerAndProducer { public static void main(String[] args) { Depot depot = new Depot(100); Producer pro = new Producer(depot); Consumer con = new Consumer(depot); pro.produce(120); pro.produce(150); con.consum(110); con.consum(120); } } class Consumer { Depot depot; public Consumer(Depot depot){ this.depot = depot; } public void consum(final int val){ new Thread(){ public void run(){ depot.consum(val); } }.start(); } } class Producer{ Depot depot; public Producer(Depot depot){ this.depot = depot; } public void produce(final int val){ new Thread(){ public void run(){ depot.produce(val); } }.start(); } }
多线程相关