多线程-管程法

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


}
发布了92 篇原创文章 · 获赞 92 · 访问量 20万+

猜你喜欢

转载自blog.csdn.net/qq_34359363/article/details/104916703