美文网首页
Java并发 | wait和notify实现生产者消费者

Java并发 | wait和notify实现生产者消费者

作者: icebreakeros | 来源:发表于2019-08-08 14:19 被阅读0次

    wait和notify实现生产者消费者

    实例

    数据对象

    /**
     * 数据对象
     */
    public class Data {
    
        private List<String> list = new ArrayList<>();
    
        synchronized public void push(String data) {
            try {
                while (list.size() != 0) {
                    this.wait();
                }
                list.add(data);
                this.notify();
                System.out.println("push: " + list.size());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    
        synchronized public String pop() {
            String result = "";
            try {
                while (list.size() == 0) {
                    this.wait();
                }
                result = list.get(0);
                list.remove(0);
                this.notify();
                System.out.println("pop: " + list.size());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return result;
        }
    }
    

    生产者

    /**
     * 生产者
     */
    public class Producer implements Runnable {
    
        private Data data;
    
        public Producer(Data data) {
            this.data = data;
        }
    
        public void service() {
            data.push("random=" + Math.random());
        }
    
        @Override
        public void run() {
            while (true) {
                service();
            }
        }
    }
    

    消费者

    /**
     * 消费者
     */
    public class Consumer implements Runnable {
    
        private Data data;
    
        public Consumer(Data data) {
            this.data = data;
        }
    
        public void service() {
            System.out.println("pop: " + data.pop());
        }
    
        @Override
        public void run() {
            while (true) {
                service();
            }
        }
    }
    

    相关文章

      网友评论

          本文标题:Java并发 | wait和notify实现生产者消费者

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