java多线程 消费者问题_Java多线程10-生产者消费者问题

classDepot

{private int capacity; //仓库容量

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

public Depot(intcapacity)

{this.capacity =capacity;this.size = 0;

}public synchronized void produce(intval)

{try{int left = val; //表示想要生产的数量

while(left > 0)

{while(size >= capacity) //仓库满了,等待消费者

wait();//计算实际增量//如果库存+想要生产的数量 > 容量,则“实际增量” = “容量” - “当前容量”(这样会填满仓库)//否则,增量 = 想要生产的数量

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

size= size +increment;

left= left -increment;

System.out.printf("%S produce(%d) --> left = %d,inc = %d, size = %d\n",

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

notifyAll();

}

}catch(InterruptedException e)

{

e.printStackTrace();

}

}public synchronized void consume(intval)

{try{int left =val;while(left > 0)

{while(size <= 0)

wait();int decrement = size < left ?size : left;

size= size -decrement;

left= left -decrement;

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

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

notifyAll();

}

}catch(InterruptedException e)

{

e.printStackTrace();

}

}publicString toString()

{return "capacity:"+capacity+", actual size:"+size;

}

}classCustomer

{privateDepot depot;publicCustomer(Depot depot)

{this.depot =depot;

}public void consume(final intval)

{newThread()

{public voidrun()

{

depot.consume(val);

}

}.start();

}

}classProducer

{privateDepot depot;publicProducer(Depot depot)

{this.depot =depot;

}public void produce(final intval)

{newThread()

{public voidrun()

{

depot.produce(val);

}

}.start();

}

}public classDemo

{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);

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值