class Goods{
public Goods() {}
}
class Producer extends Thread{
Container container;
public Producer(Container container){
this.container = container;
}
@Override
public void run() {
for(int i = 0;i<20;i++){
container.produce(new Goods());
}
}
}
class Consumer extends Thread{
Container container;
public Consumer(Container container){
this.container = container;
}
@Override
public void run() {
for(int i = 0;i<20;i++){
container.consume();
}
}
}
class Container{
private final int container_Capacity = 5;
private LinkedList<Goods> container = new LinkedList<>();
public synchronized void produce(Goods goods) {//模拟生产
while(container.size() == container_Capacity){ //当前容器的货物满了
try {
System.out.println("仓库已满");
this.wait();
}catch (Exception e){
e.printStackTrace();
}
}
container.add(goods);
System.out.println("【生产】货物,现有库存"+container.size());
this.notifyAll();
}
public synchronized void consume(){//模拟消费
while(container.size() == 0){//当前容器为空
try {
System.out.println("仓库为空");
this.wait();
}catch (Exception e){
e.printStackTrace();
}
}
container.remove();
System.out.println("【消费】货物,现有库存"+container.size());
this.notifyAll();
}
}
public class SynDemo {
public static void main(String[] args) {
Container container = new Container();
new Producer(container).start();
new Consumer(container).start();
}
}
原文:https://www.cnblogs.com/heyufeng0313/p/14732624.html