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

    经常会有公司叫我们手撕代码,比如网易,阿里,那我们是不是该掌握下呢。下面这段代码来自《现代操作系统》进程与线程P49页。

    public class ProducerConsumer {
    
        public ProducerConsumer() { }
    
        private static final int N = 100;
        static Producer producer = new Producer();
        static Consumer consumer = new Consumer();
        static Monitor monitor = new Monitor();
    
        private static class Producer extends Thread {
            @Override
            public void run() {
                //你生产的对象
                int item;
                while(true) {
                    item = produce_item();
                    monitor.insert(item);   
                }
            }
    
            public int produce_item() {
                //TODO你需要生产的对象
            }
    
        }
    
        private static class Consumer extends Thread {
            @Override
            public void run() {
                //你打算消费的对象
                int item;
                while(true) {
                    item = monitor.remove();
                    consumer_item(item);    
                }
            }
    
            private int consumer_item(int item) {
                // TODO Auto-generated method stub
            }
        }
    
        private static class Monitor {
        //存放对象的容器
            LinkedList<Integer> buffer = new LinkedList<>();
            int count =0;
            public synchronized void insert(int item) {
                if(count == N) {
                    try {
                        wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                buffer.add(item);
                count++;
                if(count == 1) {
                    notifyAll();
                }
            }
    
            public synchronized int remove() {
                if(count == 0) {
                    try {
                        wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                int val = buffer.getFirst();
                buffer.remove();
                count--;
                if(count == N-1) {
                    notifyAll();    
                }
                return val;
            }
    
        public static void main(String[] args) {
            producer.start();
            consumer.start();
        }
    }
    
  • 相关阅读:
    函数--第一类对象、闭包、
    递归
    局部变量 和 全局变量
    默认参数,不固定参数 *args,**kwargs
    函数基本语法及特性
    文件修改
    文件操作,重点,日常使用!!!
    集合
    重新写了一边三级菜单,加了一些自己的理解
    三级菜单
  • 原文地址:https://www.cnblogs.com/loren-Yang/p/7466107.html
Copyright © 2011-2022 走看看