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();
        }
    }
  • 相关阅读:
    lunix查询jdk安装路径
    (四)爬虫之动态网页
    (二)爬虫之数据提取
    图及其衍生算法(Graphs and graph algorithms)
    树及其衍生算法(Trees and tree algorithms)
    数据结构之链表(Linked list)
    查找与排序算法(Searching adn Sorting)
    数据结构之双端队列(Deque)
    数据结构之队列(Queue)
    多个git账号的SSH配置
  • 原文地址:https://www.cnblogs.com/zheng123/p/11187976.html
Copyright © 2011-2022 走看看