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

    package javalearn;
    
    import java.util.LinkedList;
    import java.util.Queue;
    
    public class ProducerConsumer {
        private static final int MAX = 5;
    
        ///////////////生产者
        public static class Producer extends Thread{
            private Queue<Integer> queue;
            int i=0;
            String name;
            int max;
            public Producer(Queue<Integer> queue,String name,int max){
                super(name);
                this.queue = queue;
                this.name = name;
                this.max = max;
            }
    
            @Override
            public void run() {
                while (true){
                    synchronized(queue){
                        while (queue.size()==max){  //停产 自旋,防止出现虚假唤醒
                            try {
                                queue.wait();
                            }catch (Exception e){
                                e.printStackTrace();
                            }
                        }
                        //继续生产
                        queue.offer(i++);
                        queue.notifyAll();
                    }
                }
            }
        }
        ///////////////消费者
        public static class Consumer extends Thread{
            private Queue<Integer> queue;
            String name;
            public Consumer(Queue<Integer>queue,String name){
                super(name);
                this.name = name;
                this.queue = queue;
            }
    
            @Override
            public void run() {
                while (true){
                    synchronized(queue){
                        while (queue.isEmpty()){    //空了就要停
                            try {
                                queue.wait();
                            }catch (Exception e){
                                e.printStackTrace();
                            }
                        }
                        queue.poll();
                        queue.notifyAll();
                    }
                }
            }
        }
        public static void main(String[] args){
            Queue<Integer>queue = new LinkedList<>();
            Thread producer1 = new Producer(queue,"P-1",MAX);
            Thread producer2 = new Producer(queue,"P-2",MAX);
            Thread consumer1 = new Consumer(queue,"C-1");
            Thread consumer2 = new Consumer(queue,"C-2");
            producer1.start();
            producer2.start();
            consumer1.start();
            consumer2.start();
        }
    }
  • 相关阅读:
    什么是ETL?5分钟看完秒懂
    横向滚动 css
    解决echarts中横坐标值显示不全(自动隐藏)问题
    Echarts
    post 二进制流下载文件
    如何停止foreach
    日期格式 js
    cookie 属性
    HTML5 file对象和blob对象的互相转换
    前端图片压缩
  • 原文地址:https://www.cnblogs.com/zheng123/p/11187976.html
Copyright © 2011-2022 走看看