美文网首页
最简单的生产者消费者demo

最简单的生产者消费者demo

作者: 我叫王菜鸟 | 来源:发表于2018-06-04 18:08 被阅读0次
    package demo1;
    import java.util.Queue;
    
    public class Consumer extends Thread {
        private final Queue sharedQ;
    
        public Consumer(Queue sharedQ) {
            super("Consumer");
            this.sharedQ = sharedQ;
        }
    
        @Override
        public void run() {
            while (true) {
                synchronized (sharedQ) {
                    while (sharedQ.size() == 0) {
                        try {
    //                        System.out.println("Queue is empty, waiting");
                            sharedQ.wait();
                        } catch (InterruptedException ex) {
                            ex.printStackTrace();
                        }
                    }
                    int number = (int) sharedQ.poll();
                    System.out.println("consuming : " + number);
                    sharedQ.notify();
                    if (number == 3) {
                        break;
                    }
                }
            }
        }
    }
    
    package demo1;
    import java.util.Queue;
    
    public class Producer extends Thread {
        private final Queue sharedQ;
    
        public Producer(Queue sharedQ) {
            super("Producer");
            this.sharedQ = sharedQ;
        }
    
        @Override
        public void run() {
    
            for (int i = 0; i < 4; i++) {
                synchronized (sharedQ) {
                    while (sharedQ.size() >= 1) {
                        try {
    //                        System.out.println("Queue is full, waiting");
                            sharedQ.wait();
                        } catch (InterruptedException ex) {
                            ex.printStackTrace();
                        }
                    }
                    System.out.println("producing : " + i);
                    sharedQ.add(i);
                    sharedQ.notify();
                }
            }
        }
    }
    
    package demo1;
    import java.util.LinkedList;
    import java.util.Queue;
    
    public class Test {
        public static void main(String[] args) {
            final Queue sharedQ = new LinkedList();
            Thread producer = new Producer(sharedQ);
            Thread consumer = new Consumer(sharedQ);
    
            producer.start();
            consumer.start();
        }
    }
    

    相关文章

      网友评论

          本文标题:最简单的生产者消费者demo

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