• 生产者和消费者


    管程法

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

    /**
     * 生产者消费者之管程法
     */
        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;
        }
    
    
  • 相关阅读:
    HeadFirst Ruby 第七章总结 references
    《HTTP 权威指南》笔记:第三章 HTTP 报文
    HTTP 权威指南 第二章 URL 与资源
    HeadFIrst Ruby 第七章总结 hashes
    HeadFIrst Ruby 第六章总结 block return values
    面向对象的面试题
    属性,类方法,静态方法,Python2和3方法
    类的抽象类接口类,多态封装
    类的继承
    面向对象空间和组合
  • 原文地址:https://www.cnblogs.com/dakuzai/p/13362785.html
Copyright © 2020-2023  润新知