首页 > 代码库 > 生产者消费者问题
生产者消费者问题
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\n", 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\n", 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(); }}
多线程相关
生产者消费者问题
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。