多线程实现消费者生产者模型

多线程实现生产者和消费者模型

原理解析

实现该模型的关键点在于使用wait()和notify()方法进行线程的切换,话不多说,直接上代码

缓存类

/**
 * @Author: guanghui
 * @DateTime: 2021/9/18 15:15
 */
public class Quene {
	//用于判断数组是否满了
    private int index=0;
    //数组长度
    private int size=10;
    //用于存储数据
    private Byte[] bytes;

    public Quene(int size){
        this.size=size;
        this.bytes=new Byte[size];
    }

    //生产数据
    public  synchronized void push(byte c) throws InterruptedException {
        while(index==size){
            //数据存满了,需要进入阻塞状态
            System.out.println("数据满了,通知消费执行");
            //哪个线程调用push方法就会被阻塞
            this.wait();
        }
        //赋值
        bytes[index]=c;
        //自增
        index++;
        //已经生产了数据,通知消费者消费
        this.notify();
    }

    //消费数据
    public  synchronized void pop() throws InterruptedException {
        while(index==0){
            //数据消费完了
            System.out.println("数据消费完了,通知生产者生产");
            this.wait();
        }
        index--;
        this.notify();
    }
}

生产者

import lombok.SneakyThrows;

import java.util.Random;

/**
 * @Author: guanghui
 * @DateTime: 2021/9/18 14:42
 */
public class Provider implements Runnable{
    private Quene quene;

    public Provider(Quene quene){
        this.quene=quene;
    }
    //不想写try catch
    @SneakyThrows
    @Override
    public void run() {
        for (int i=0;i<10;i++){
            quene.push((byte) i);
            System.out.println("生产"+i);
        }
    }
}

消费者

package com.guanghui.provider.thread;

import lombok.SneakyThrows;

/**
 * @Author: guanghui
 * @DateTime: 2021/9/18 14:52
 */
public class Consumer implements Runnable{
    private Quene quene;

    public Consumer(Quene quene){
        this.quene=quene;
    }
    @SneakyThrows
    @Override
    public void run() {
        for (int i=0;i<10;i++){
            quene.pop();
            System.out.println("消费"+i);
        }
    }
}

测试类

/**
 * @Author: guanghui
 * @DateTime: 2021/9/18 14:59
 */
public class Test {
    public static void main(String[] args){
       Quene q=new Quene(10);
        Thread threadC=new Thread(new Consumer(q));
        Thread threadP=new Thread(new Provider(q));

        threadC.start();
        threadP.start();

    }
}

输出结果


我们可以看到控制台打印的生产一个数据消费一个数据,在打印时间上可能会有误差,但是实际执行流程是顺序的。这是一个最简单的实现生产者消费者模型的方法,关键点在于理解wait()和notify()运行机制。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值