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