package com.test.Thread;
/*
测试生产者消费者模型-->利用缓冲区解决:管程法
生产者,消费者,产品,缓冲区
*/
public class TestPC {
public static void main(String[] args) {
SysContainer container =new SysContainer();
new Productor(container).start();
new Consumer(container).start();
}
}
//生产者类
class Productor extends Thread{
SysContainer container;
public Productor(SysContainer container) {
this.container = container;
}
//生产鸡!
@Override
public void run(){
for (int i = 0; i < 100; i++) {
System.out.println("生产了"+i+"只鸡");
container.push(new Chicken(i));
}
}
}
//消费者类
class Consumer extends Thread{
SysContainer container;
public Consumer(SysContainer container) {
this.container = container;
}
//消费者消费
@Override
public void run() {
//消费
for (int i = 0; i < 100; i++) {
System.out.println("消费了-->"+container.pop().id+"只鸡");
}
}
}
//产品类
class Chicken{
int id;//生产编号
public Chicken(int id){
this.id=id;
}
}
class SysContainer{
//设定容器大小
Chicken[] chickens=new Chicken[9];
//容器计数器
int count=0;
//消费者负责生产鸡
public synchronized void push(Chicken chicken){
//如果生产的鸡到达了容器大小,停止生产等待消费者消费
if(count==chickens.length){
//生产者等待
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//容器没有满,就放入产品
chickens[count]=chicken;
count++;
//通知消费者消费
this.notifyAll();
}
//消费者消费
public synchronized Chicken pop(){
//判断是否有鸡
if(count==0){
try {
//没有鸡等待
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//有鸡就可以消费
count--;
Chicken chicken =chickens[count];
//唤醒生产者生产
this.notifyAll();
return chicken;
}
}
使用管程法解决生产者消费者问题
最新推荐文章于 2022-04-02 14:00:00 发布