美文网首页
生产者、消费者

生产者、消费者

作者: 一只好奇的茂 | 来源:发表于2018-05-06 10:26 被阅读10次
    public class Storage {
        private LinkedList<String> mStringLinkedList = new LinkedList<>();
        private int MAX = 10;
        private static final String TAG = "zhoumao";
    
        public void consume() {
            synchronized (mStringLinkedList) {
                while (mStringLinkedList.size() == 0) {
                    try {
                        Log.d(TAG, "consume: " + mStringLinkedList.size());
                        mStringLinkedList.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                Log.d(TAG, "consume: " + mStringLinkedList.remove());
                mStringLinkedList.remove();
                mStringLinkedList.notifyAll();
            }
        }
    
        public void product() {
            synchronized (mStringLinkedList) {
                while (mStringLinkedList.size() == MAX) {
                    try {
                        Log.d(TAG, "product: " + mStringLinkedList.size());
                        mStringLinkedList.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                Log.d(TAG, "product: " + mStringLinkedList.add("abc"));
                mStringLinkedList.add("abc");
                mStringLinkedList.notifyAll();
            }
        }
    }
    
    public class Consumer extends Thread {
        Storage mStorage;
    
        public Consumer(Storage storage) {
            this.mStorage = storage;
        }
    
        @Override
        public void run() {
            mStorage.consume();
        }
    }
    
    public class Productor extends Thread {
    
        Storage mStorage;
    
        public Productor(Storage storage) {
            this.mStorage = storage;
        }
    
        @Override
        public void run() {
            mStorage.product();
        }
    }
    

    测试代码

         Storage storage=new Storage();
            new Consumer(storage).start();
            new Productor(storage).start();
            for (int i =0;i<10;i++){
                new Productor(storage).start();
            }
            new Consumer(storage).start();
            new Productor(storage).start();
            new Consumer(storage).start();
            new Productor(storage).start();
    

    附:
    如何处理InterruptedException异常

    相关文章

      网友评论

          本文标题:生产者、消费者

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