//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);
}
}