博主
258
258
258
258
专辑

第七节 多线程并发协作模型:管程法

亮子 2021-10-13 20:43:01 6676 0 0 0

01 生产者-消费者模型

理解:生产者将生产好的数据放入缓冲区 , 消费者从缓冲区拿出数据。通过判断缓冲区大小来决定生产者何时生产,消费者何时消费。只要缓冲区有产品,消费者就可以消费。只要缓冲区不满,生产者就可以生产。

模型:
- 生产者 : 负责生产数据的模块 (可能是方法 , 对象 , 线程 , 进程) ;
- 消费者 : 负责处理数据的模块 (可能是方法 , 对象 , 线程 , 进程) ;
- 缓冲区 : 消费者不能直接使用生产者的数据 , 而是通过缓冲区拿出数据。

02 案例

案例说明:生产者生产产品,将产品放入缓冲区,消费者通过缓冲区消费产品。

package com.shenmazong;

/**
 * @author 军哥
 * @version 1.0
 * @description: 并发协作模型:管程法
 * @date 2021/10/13 20:38
 */

//--1 产品
class Product{
    //产品编号
    int id;

    public Product(int id) {
        this.id = id;
    }
}


//--2 缓冲区-----容器
class SynContainer{

    //定义容器容量
    Product[] products = new Product[10];
    //定义产品索引,通过索引拿到产品
    int index=0;
    //生产者放入产品
    public synchronized void push(Product product){
        //1.如果容器满了,不再放入产品,等待消费者消费
        if (index>=products.length){
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        //2.如果容器没有装满,生产者生产
        products[index]=product;//给容器中放入产品
        index++;
        //装入产品后,通知消费者消费
        this.notifyAll();//notifyAll()唤醒同一个对象上所有调用wait()方法的线程

    }
    //消费者拿走产品
    public synchronized Product pop(){
        // 如果容器为空,通知生产者生产,等待生产者放入产品
        if (index<=0){
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        //容器不为空,消费者消费
        index--;
        Product product = products[index];
        //此时容器不满,通知生产者生产
        this.notifyAll();
        //将产品返回给消费者
        return product;


    }
}

//--3 生产者只负责给容器中放入产品
class Producer extends Thread{
    //需要向容器中加入产品
    //定义一个容器
    SynContainer container;
    public Producer(SynContainer container){
        this.container=container;
    }
    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            //生产100次产品
            //给容器添加产品
            container.push(new Product(i));
            System.out.println("生产者放入了产品编号为:"+i+"的产品");
        }
    }
}

//--4 消费者只负责从容器中拿出产品
class Consumer extends Thread{
    //通过容器操作
    SynContainer container;
    //通过有参构造传入容器
    public Consumer(SynContainer container){
        this.container=container;
    }
    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            //一次线程消费100次
            //调用容器,取产品
            Product product = container.pop();
            System.out.println("消费者拿走了产品编号为:"+product.id+"的产品");
        }
    }
}


public class DemoThread03 {
    public static void main(String[] args) {
        // 建立一个容器
        SynContainer synContainer = new SynContainer();
        new Producer(synContainer).start();
        new Consumer(synContainer).start();
    }
}

03 运行结果

运行结果

参考文档: