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