美文网首页
Java使用wait和notify实现生产者消费者模式

Java使用wait和notify实现生产者消费者模式

作者: _灯火阑珊处 | 来源:发表于2020-06-16 17:16 被阅读0次

    用wait和notify实现生产者消费者模式示例代码

    import java.util.Date;
    import java.util.LinkedList;
    
    /**
     * 用wait和notify实现生产者消费者模式
     */
    public class ProducerConsumerModel {
        public static void main(String[] args) {
            EventStorage storage = new EventStorage();
            Producer producer = new Producer(storage);
            Consumer consumer = new Consumer(storage);
            new Thread(producer).start();
            new Thread(consumer).start();
        }
    }
    
    /**
     * 生产者
     */
    class Producer implements Runnable {
    
        private EventStorage storage;
    
        public Producer(EventStorage storage) {
            this.storage = storage;
        }
    
        @Override
        public void run() {
            for (int i = 0; i < 100; i++) {
                storage.put();
            }
        }
    }
    
    /**
     * 消费者
     */
    class Consumer implements Runnable {
    
        private EventStorage storage;
    
        public Consumer(EventStorage storage) {
            this.storage = storage;
        }
    
        @Override
        public void run() {
            for (int i = 0; i < 100; i++) {
                storage.take();
            }
        }
    }
    
    /**
     * 仓库
     */
    class EventStorage {
        private int maxSize;
        private LinkedList<Date> storage;
    
        public EventStorage() {
            maxSize = 10;
            storage = new LinkedList<>();
        }
    
        public synchronized void put() {
            while (storage.size() == maxSize) {
                try {
                    wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            storage.add(new Date());
            System.out.println("仓库里有了" + storage.size() + "个产品。");
            notify();
        }
    
        public synchronized void take() {
            while (storage.size() == 0) {
                try {
                    wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println("拿到了" + storage.poll() + ",现在仓库还剩下" + storage.size());
            notify();
        }
    }
    

    相关文章

      网友评论

          本文标题:Java使用wait和notify实现生产者消费者模式

          本文链接:https://www.haomeiwen.com/subject/nqprxktx.html