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

    简介

    生产者消费者模式通过 缓冲区实现

    code

    package com.kuang;
    
    import com.sun.corba.se.impl.orbutil.concurrent.Sync;
    
    /**
     * Created by lee on 2021/3/30.
     */
    // 测试利用缓冲区解决
    public class TestPC {
        public static void main(String[] args) throws InterruptedException {
            SynContainer container = new SynContainer();
            new Productor(container).start();
            new Consumer(container).start();
            Thread.sleep(10000);
        }
    }
    
    class Productor extends Thread {
        SynContainer container;
        public Productor(SynContainer container) {
            this.container = container;
    
        }
        @Override
        public void run() {
            for (int i = 0; i < 100; i++) {
                container.push(new Chicken(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 Chicken{
        int id;
        public Chicken(int i_){
            id = i_;
        }
    }
    // 缓冲区
    class SynContainer {
        // 需要一个容器大小
        Chicken [] chickends = new Chicken[100];
        int count = 0;
        // 生产者放入产品
        public synchronized void push(Chicken chicken) {
            //如果容器满了,就需要等待消费
            if(count == chickends.length) {
                // 通知消费者消费,生产等待
                try {
                    this.wait();
                } catch(InterruptedException e){
                    e.printStackTrace();
                }
            }
            // 如果没有满,我们就需要丢入产品
            chickends[count] = chicken;
            count++;
    
    
            this.notifyAll();
        }
    
        public synchronized Chicken pop() {
            if(count == 0) {
                // 等待生产者生产,消费者等待
                try {
                    this.wait();
                } catch(InterruptedException e){
                    e.printStackTrace();
                }
            }
            count--;
            Chicken chicken = chickends[count];
    
            // 吃完了,通知生产者生产
            this.notifyAll();
            return chicken;
        }
    }
    
    Hope is a good thing,maybe the best of things,and no good thing ever dies.----------- Andy Dufresne
  • 相关阅读:
    高德地图的使用点标记、折线标记
    vue 过滤器filter(全面)
    vue cli4.0 快速搭建项目详解
    vue cli3.0快速搭建项目详解(强烈推荐)
    路由传参的三种方法
    router-link 返回上页 和 新窗口打开链接
    Django REST framework+Vue 打造生鲜超市(一)
    Android笔记:波纹按钮
    简单更换博客园背景
    SUID,SGID和SBIT
  • 原文地址:https://www.cnblogs.com/eat-too-much/p/14599480.html
Copyright © 2011-2022 走看看