java多线程库存量,Java多线程系列---“基础篇”11之 生产消费者问题

//Demo1.java//仓库

classDepot {private int capacity; //仓库的容量

private int size; //仓库的实际数量

public Depot(intcapacity) {this.capacity =capacity;this.size = 0;

}public synchronized void produce(intval) {try{//left 表示“想要生产的数量”(有可能生产量太多,需多今生产)

int left =val;while (left > 0) {//库存已满时,等待“消费者”消费产品。

while (size >=capacity)

wait();//获取“实际生产的数量”(即库存中新增的数量)//若是“库存”+“想要生产的数量”>“总的容量”,则“实际增量”=“总的容量”-“当前容量”。(此时填满仓库)//不然“实际增量”=“想要生产的数量”

int inc = (size+left)>capacity ? (capacity-size) : left;

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(InterruptedException e) {

}

}public synchronized void consume(intval) {try{//left 表示“客户要消费数量”(有可能消费量太大,库存不够,需多此消费)

int left =val;while (left > 0) {//库存为0时,等待“生产者”生产产品。

while (size <= 0)

wait();//获取“实际消费的数量”(即库存中实际减小的数量)//若是“库存”

int dec = (size

size-=dec;

left-=dec;

System.out.printf("%s consume(%3d)

Thread.currentThread().getName(), val, left, dec, size);

notifyAll();

}

}catch(InterruptedException e) {

}

}publicString toString() {return "capacity:"+capacity+", actual size:"+size;

}

}//生产者

classProducer {privateDepot depot;publicProducer(Depot depot) {this.depot =depot;

}//消费产品:新建一个线程向仓库中生产产品。

public void produce(final intval) {newThread() {public voidrun() {

depot.produce(val);

}

}.start();

}

}//消费者

classCustomer {privateDepot depot;publicCustomer(Depot depot) {this.depot =depot;

}//消费产品:新建一个线程从仓库中消费产品。

public void consume(final intval) {newThread() {public voidrun() {

depot.consume(val);

}

}.start();

}

}public classDemo1 {public static voidmain(String[] args) {

Depot mDepot= new Depot(100);

Producer mPro= newProducer(mDepot);

Customer mCus= newCustomer(mDepot);

mPro.produce(60);

mPro.produce(120);

mCus.consume(90);

mCus.consume(150);

mPro.produce(110);

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值