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;
        }
    
    
  • 相关阅读:
    记一次阿里云硬盘在线扩容
    大文件传输技巧-----split切割
    数据库迁移-------通过ibdata1文件和数据库文件迁移
    小技巧---------------vim 使用技巧 set paste 解决粘贴乱序问题
    webfrom 做项目的注意事项
    webform 复合控件
    wenfrom的简单控件和repeater控件
    分页功能 与 分类查询功能合并
    内置对象2
    简单的人员管理系统
  • 原文地址:https://www.cnblogs.com/dakuzai/p/13362785.html
Copyright © 2011-2022 走看看