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();
    }
}
原文地址:https://www.cnblogs.com/loren-Yang/p/7466107.html