多線程-管程法

package com.example.test1.test;

/**
 * @Auther: DELL
 * @Date: 2020/3/17 10:18
 * @Description:
 */
public class testCCModel{
    public static void main(String[] args) {
        SynContainer container=new SynContainer();
        new Productor(container).start();
        new Customer(container).start();
    }



}
//生產者
class Productor extends Thread{
    SynContainer SynContainer;

  
    public Productor(SynContainer SynContainer){
        this.SynContainer=SynContainer;
    }
    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            System.out.println("生成了"+i+"只雞");
            SynContainer.push(new check(i));
        }
    }

}

//生產者
class Customer extends Thread{

    SynContainer SynContainer;


    public Customer(SynContainer SynContainer){
        this.SynContainer=SynContainer;
    }
    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            System.out.println("消費了"+SynContainer.pop().i);
        }
    }

}
//產品
class check{
    int i; //產品編號
    public  check(int a ){
        this.i=a;
    }


}
//緩衝區
class SynContainer{

    //容器大小
    check a[]=new check[10];
    //現有數量
    int count=0;
    //生產者放入產品
    public synchronized  void push(check check){
     if (count==a.length){
         //如果容器滿了,生成者需要等待,消費者繼續
         try {
             this.wait();
         } catch (InterruptedException e) {
             e.printStackTrace();
         }
     }
     a[count]=check;
     count++;
     this.notifyAll();
    }

    public synchronized  check pop(){
        if (count==0){
            //等待生產者生成,
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        count--;
        check check=a[count];
        this.notifyAll();
        return check;
    }


}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章