多线程-管程法

多线程-管程法

package basic;

import java.util.zip.CheckedInputStream;

public class TestPC {
    public static void main(String[] args) {
        CContainer cc = new CContainer();
        new Productor(cc).start();
        new Consumer(cc).start();
    }
}

class Productor extends Thread{
    private CContainer cc ;
    public Productor(CContainer cc){
        this.cc = cc;
    }

    @Override
    public void run() {
        super.run();
        for(int i=1;i<=100;i++){
            cc.push(new Chicken(i));

        }
    }
}

class Consumer extends Thread{
    private CContainer cc ;
    public Consumer(CContainer cc){
        this.cc = cc;
    }
    @Override
    public void run() {
        super.run();
        for(int i=1;i<=100;i++){
            Chicken chicken = cc.pop();
        }

    }
}

class Chicken{
    private int i;

    public int getI() {
        return i;
    }

    public void setI(int i) {
        this.i = i;
    }

    public Chicken(int i) {
        this.i = i;
    }
}

class CContainer{
    int count = 0;
    Chicken[] chickens = new Chicken[10];
    public synchronized void  push(Chicken chicken){
        while(count==10){
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        chickens[count++] = chicken;
        System.out.println("生产者生产了第"+chicken.getI()+"只鸡");
        this.notifyAll();



    }

    public synchronized  Chicken pop(){
        Chicken chicken = null;
        while(count==0){
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        chicken = chickens[--count];
        System.out.println("消费者消费了第"+chicken.getI()+"只鸡");
        this.notifyAll();

        return chicken;
    }
}
posted @ 2021-03-23 06:50  天然卷123  阅读(0)  评论(0)    收藏  举报