美文网首页
生产者消费者模式

生产者消费者模式

作者: Wide_Star | 来源:发表于2018-05-24 16:00 被阅读0次

    开始


    package multithread;
    
    import java.util.LinkedList;
    import java.util.List;
    
    public class ProducterAndConsumer {
    
        static class Storage{
            //仓库最大容量
            private final int MAX_SIZE=10;
            //仓库存储的数据结构:集合
            private List<String> list=new LinkedList<>();
            public synchronized void produce(int i) {
                while(list.size()==MAX_SIZE) {
                    System.out.println("仓库已满,暂时不能生产");
                    try {
                        wait();
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
                String s=i+"";
                list.add(s);
                System.out.println("生产了产品-->"+s);
                notify();
                
            }
            public synchronized void consume() {
                while(list.size()==0) {
                    System.out.println("仓库以空,暂时不能消费");
                    try {
                        wait();
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
                System.out.println("消费了产品-->"+list.remove(list.size()-1));
                notify();
            }
            
        }
        static class Producer implements Runnable
        {
            private Storage s;
            public Producer(Storage s) {
                // TODO Auto-generated constructor stub
                this.s=s;
            }
            @Override
            public void run() {
                // TODO Auto-generated method stub
                for (int i = 0; i < 30; i++) {
                    s.produce(i);
                }
            }
            
        }
        static class Consumer implements Runnable{
            private Storage s;
            public Consumer(Storage s) {
                // TODO Auto-generated constructor stub
                this.s=s;
            }
            @Override
            public void run() {
                // TODO Auto-generated method stub
                for(int i=0;i<30;i++) {
                    s.consume();
                }
            }
        }
        public static void main(String[] args) {
            // TODO Auto-generated method stub
            Storage storage=new Storage();
            new Thread(new Consumer(storage)).start();
            new Thread(new Producer(storage)).start();
        }
    }
    

    结束

    相关文章

      网友评论

          本文标题:生产者消费者模式

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