import java.util.*;
public class Test6 {
    public static void main(String[] args){
        Buffer bu=new Buffer();
        Production pro=new Production(bu);
        Consumption con=new Consumption(bu);

        new Thread(pro).start();
        new Thread(con).start();
    }
}

//自定义临界区
class Buffer{
    //数据缓冲区
    private LinkedList<Integer> list=new LinkedList<Integer>();
    //设定缓冲区最大容量
    private final int max=20;
    //生产者方法
    public synchronized void Production(Integer product){
        try{
            while(list.size()>=max){
                this.wait();
            }
            list.add(product);
            System.out.println("生产信息:"+product+"完成");
            this.notify();
        }catch(Exception e){
            e.printStackTrace();
        }
    }
    //消费者方法
    public synchronized void Consumption(){
        try{
            while(list.size()<=0){
                this.wait();
            }
            Integer consume=list.removeFirst();
            System.out.println("产品"+consume+"已被消费");
            this.notify();
        }catch(Exception e){
            e.printStackTrace();
        }
    }
}

//自定义生产者线程
class Production implements Runnable{
    private Integer product=0;
    private Buffer bu;
    public Production(Buffer bu){
        this.bu=bu;
    }
    public void run(){
        while(true){
            bu.Production(product++);
        }
    }
}

//自定义消费者线程
class Consumption implements Runnable{
    private Buffer bu;
    public Consumption(Buffer bu){
        this.bu=bu;
    }
    public void run(){
        while(true){
            bu.Consumption();
        }
    }
}