简介

生产者消费者模式通过 缓冲区实现

code

package com.kuang;

import com.sun.corba.se.impl.orbutil.concurrent.Sync;

/**
 * Created by lee on 2021/3/30.
 */
// 测试利用缓冲区解决
public class TestPC {
    public static void main(String[] args) throws InterruptedException {
        SynContainer container = new SynContainer();
        new Productor(container).start();
        new Consumer(container).start();
        Thread.sleep(10000);
    }
}

class Productor extends Thread {
    SynContainer container;
    public Productor(SynContainer container) {
        this.container = container;

    }
    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            container.push(new Chicken(i));
            System.out.println("生产了" + i + "只鸡");

        }
    }

}

class Consumer extends Thread {
    SynContainer container;
    public Consumer(SynContainer 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 i_){
        id = i_;
    }
}
// 缓冲区
class SynContainer {
    // 需要一个容器大小
    Chicken [] chickends = new Chicken[100];
    int count = 0;
    // 生产者放入产品
    public synchronized void push(Chicken chicken) {
        //如果容器满了,就需要等待消费
        if(count == chickends.length) {
            // 通知消费者消费,生产等待
            try {
                this.wait();
            } catch(InterruptedException e){
                e.printStackTrace();
            }
        }
        // 如果没有满,我们就需要丢入产品
        chickends[count] = chicken;
        count++;


        this.notifyAll();
    }

    public synchronized Chicken pop() {
        if(count == 0) {
            // 等待生产者生产,消费者等待
            try {
                this.wait();
            } catch(InterruptedException e){
                e.printStackTrace();
            }
        }
        count--;
        Chicken chicken = chickends[count];

        // 吃完了,通知生产者生产
        this.notifyAll();
        return chicken;
    }
}
posted on 2021-03-30 23:31  HDU李少帅  阅读(84)  评论(0编辑  收藏  举报