首页 > 其他分享 >生产者消费者模式

生产者消费者模式

时间:2022-10-20 20:56:32浏览次数:45  
标签:index Resource Contanier 生产者 模式 contanier public resources 消费者

生产者消费者模式(Java实现)

  1. 定义

    在⼀个⽣产环境中,⽣产者和消费者在同⼀时间段内共享同⼀块缓冲区,⽣产者负责向缓冲区添加数 据,消费者负责从缓冲区取出数据

  2. 使用

    资源类:

    /**
     * 资源类
     */
    public class Resource {
        private int id;
    
        public Resource(int id) {
            this.id = id;
        }
    
        @Override
        public String toString() {
            return "Resource{" +
                    "id=" + id +
                    '}';
        }
    }
    

    容器类

    /**
     * 容器类
     */
    public class Contanier {
        //30个位置
        private  Resource[] resources = new Resource[30];
        private static final Integer mutex = 0;
        private int index = 0;
        public Contanier(Resource[] resources) {
            this.resources = resources;
        }
    
        public Contanier() {
    
        }
    
        public synchronized boolean push(Resource resource){
            //此处相当于P(empty) 不用减1因为当等于29个时候时候会有个index++操作 如果是==length-1那会少存一个
            while (index==resources.length){
                try {
                    this.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            //此处相当于P(mutex)
            synchronized(Contanier.mutex){
                resources[index] = resource;
                System.out.println(Thread.currentThread().getName()+"生产了一个资源"+resources[index]);
                //此处相当于V(full)
                index++;
                this.notify();
                return true;
                //代码执行完 就是V(mutex)
            }
        }
        public synchronized boolean pop(){
            //此处相当于P(full)
            while (index==0){
                try {
                    this.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            //此处相当于P(mutex)
            synchronized (Contanier.mutex){
                index--;
                System.out.println(Thread.currentThread().getName()+"输出了一个资源"+resources[index]);
                resources[index] = null;
                //此处相当于V(empty)
                this.notify();
                return true;
                //代码执行完 就是V(mutex)
            }
        }
    }
    

    生产者类

    import java.util.concurrent.TimeUnit;
    /**
     * 生产者
     */
    public class Producer {
        //生产者需要容器的
        private Contanier contanier;
        public Producer(Contanier contanier) {
            this.contanier = contanier;
        }
    
        public boolean product(){
            for (int i = 0; i < 30; i++) {
                //生产一个资源类
                Resource resource = new Resource(i);
                //生产一个资源是需要时间的
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                //生产完放入容器类中
                this.contanier.push(resource);
    
            }
            return true;
        }
    }
    

    消费者类

    import java.util.concurrent.TimeUnit;
    /**
     * 消费者
     */
    public class Consumer {
        //消费者也需要一个容器
        private Contanier contanier ;
    
        public Consumer(Contanier contanier) {
            this.contanier = contanier;
        }
        public boolean consume (){
            for (int i = 0; i < 30; i++) {
                this.contanier.pop();
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            return true;
        }
    }
    

    测试类

    /**
     * 测试类
     */
    public class Main {
        public static void main(String[] args) {
            Contanier contanier = new Contanier();
            //生产者消费者用的是同一个容器 所以传同一个容器对象进去
            Producer producer = new Producer(contanier);
            Consumer consumer = new Consumer(contanier);
            //一个线程生产 一个线程消耗
            new Thread(()->{
                producer.product();
            },"生产者线程").start();
            new Thread(()->{
                consumer.consume();
            },"消费者线程").start();
        }
    }
    

标签:index,Resource,Contanier,生产者,模式,contanier,public,resources,消费者
From: https://www.cnblogs.com/zwl-/p/16811234.html

相关文章

  • 单例模式在 Runtime 类中的应用
    JDK中java.lang.Runtime类是一个单例类每个Java应用在运行时会启动一个JVM进程,每个JVM进程都只对应一个Runtime实例,用于查看JVM状态以及控制JVM行为。进程......
  • 观察者模式在 JDK 中的应用
    GoogleGuava的EventBus框架,它提供了观察者模式的骨架代码。使用EventBus,不需要从零开始开发观察者模式。实际上,JavaJDK也提供了观察者模式的简单框架实现。在平时的......
  • 设计模式之单例模式
    简介在实际开发中,为了节约系统资源,有时需要确保系统中某个类只有唯一一个实例,当这个唯一实例创建成功之后,无法再创建一个同类型的其他对象,所有的操作都只能基于这个唯一实......
  • Tutorial 6_原型模式
    向量的原型用C++完成数学中向量的封装,其中,用指针和动态申请支持向量长度的改变,使用浅克隆和深克隆复制向量类,比较这两种克隆方式的异同。浅克隆  深克隆  ......
  • Tutorial 7_单例模式
    学号的单一仿照课堂的身份证的例子,实现每个同学仅有一个学号这一问题。类图  代码  2.1StudentID.javapackagedanli;publicclassStudentID{......
  • Tutorial 8_适配器模式
    双向适配器实现一个双向适配器,使得猫可以学狗叫,狗可以学猫抓老鼠。  代码  ICat.javapackageshipeiqi;publicinterfaceICat{publicvoideat()......
  • Tutorial 9_桥接模式
    两个维度的桥接模式用桥接模式实现在路上开车这个问题,其中,车可以是car或bus,路可以是水泥路或沥青路。类图  代码Vehicle.javapackageqiaojie;publicinterfa......
  • Collections 类中设计模式的应用
    装饰器模式Collections类是一个集合容器的工具类,提供了很多静态方法,用来创建各种集合容器,比如通过unmodifiableColletion()静态方法,来创建UnmodifiableCollection类......
  • Calendar 类中设计模式的应用
    包名:java.util.Calendar工厂模式Calendar类提供了大量跟日期相关的功能代码,同时,又提供了一个getInstance()工厂方法,用来根据不同的TimeZone和Locale创建不同的Ca......
  • 享元模式
    实验13:享元模式本次实验属于模仿型实验,通过本次实验学生将掌握以下内容:1、理解享元模式的动机,掌握该模式的结构;2、能够利用享元模式解决实际问题。   ......