java多線程-生產者和消費者模式

java多線程-生產者和消費者模式

方法

利用 生產者和消費者,共享一個 空間,
生產者 生產 的放進這個空間,
而消費者等待 生產者 生產並放入空間,然後再進入獲取

而 這個空間,可以稱之爲 緩衝區

下面是例子,可以進行復習

package com.demo.practice;

/**
 * @version : 1.0
 * @auther : Firewine
 * @Program Name: CoTest01
 * @Create : 2019/12/29
 * @Description :
 */
public class CoTest01 {
    public static void main(String[] args) {
        SynContainer1 container = new SynContainer1();
        new Productor(container).start();
        new Consumer(container).start();
    }
}
//生產者
class Productor extends Thread{
    SynContainer1 container  ;
    public Productor(SynContainer1 container) {
        this.container = container;
    }

    @Override
    public void run() {
        //生產
        for(int i=0;i<100;i++) {
            System.out.println("生產-->"+i+"個饅頭");
            container.push(new Steamedbun(i) );
        }
    }
}
//消費者
class Consumer extends Thread{
    SynContainer1 container  ;
    public Consumer(SynContainer1 container) {
        this.container = container;
    }
    @Override
    public void run() {
        //消費
        for(int i=0;i<100;i++) {
            System.out.println("消費-->"+container.pop().id+"個饅頭");
        }
    }
}
//緩衝區
class SynContainer1{
    Steamedbun[] buns = new Steamedbun[10]; //存儲容器
    int count = 0; //計數器
    //存儲 生產
    public synchronized void push(Steamedbun bun) {
        //何時能生產  容器存在空間
        //不能生產 只有等待
        if(count == buns.length) {
            try {
                this.wait(); //線程阻塞  消費者通知生產解除
            } catch (InterruptedException e) {
            }
        }
        //存在空間 可以生產
        buns[count] = bun;
        count++;
        //存在數據了,可以通知消費了
        this.notifyAll();
    }
    //獲取 消費
    public synchronized Steamedbun pop() {
        //何時消費 容器中是否存在數據
        //沒有數據 只有等待
        if(count == 0) {
            try {
                this.wait(); //線程阻塞  生產者通知消費解除
            } catch (InterruptedException e) {
            }
        }
        //存在數據可以消費
        count --;
        Steamedbun bun = buns[count] ;
        this.notifyAll(); //存在空間了,可以喚醒對方生產了
        return bun;
    }
}
//饅頭
class Steamedbun{
    int id;
    public Steamedbun(int id) {
        this.id = id;
    }

}




發佈了79 篇原創文章 · 獲贊 22 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章