zoukankan      html  css  js  c++  java
  • 生产者和消费者

    管程法

    利用缓冲区来解决生产者消费者问题

    /**
     * 生产者消费者之管程法
     */
        public static void main(String[] args) {
            //缓冲区
            SynContainer synContainer = new SynContainer();
            new Producer(synContainer).start();
            new Consumer(synContainer).start();
        }
    }
    
    //产品
    class Product {
        int id;
    
        public Product(int id) {
            this.id = id;
        }
    }
    
    //生产者
    class Producer extends Thread {
        //缓冲区对象
        SynContainer container;
    
        public Producer(SynContainer container) {
            this.container = container;
        }
    
        //生产
        @Override
        public void run() {
            for (int i = 0; i < 100; i++) {
                //调用生产方法
                container.push(new Product(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 SynContainer {
        //容器
        Product[] products = new Product[10];
        //容器计数器
        int count = 0;
    
        //生产者生产
        public synchronized void push(Product product) {
            //判断是否已经达到生产满了,满了就等待,让消费者消费
            if (count == products.length) {
                try {
                    this.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            //开始生产并将产品放入容器
            products[count] = product;
            //计数
            count++;
            //通知消费者消费
            this.notifyAll();
        }
    
        //消费者消费(需要返回消费数量)
        public synchronized Product pop() {
            //判断是否有产品可以消费,没有就等待,通知生产者生产
            if (count == 0) {
                try {
                    this.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            //开始消费
            count--;
            //返回消费信息
            Product product = products[count];
            //通知生产者生产
            this.notifyAll();
            return product;
        }
    
    
  • 相关阅读:
    MCU软件最佳实践——独立按键
    MCU软件最佳实践——矩阵键盘驱动
    MCU软件最佳实践——使用printf打印数据
    CAP定理图解证明
    类型和变量
    数字ID过长 精度丢失 (已解决:后端方案)
    Springboot 异步线程池配置(小型应用)
    Java 数字 字符串 简单操作
    Java 网络请求
    Java 时间 日 周 月 季 年
  • 原文地址:https://www.cnblogs.com/dakuzai/p/13362785.html
Copyright © 2011-2022 走看看