zoukankan      html  css  js  c++  java
  • 使用wait/notify实现生产消费模型

    public class A {
        private Deque<Integer> list = new LinkedList<>();
        private int max = 10;
        private int size = 0;
    
        public synchronized int consumer() {
            System.out.println(Thread.currentThread().getName());
            // 不要用if
            while (size == 0) {
                try {
                    System.out.println("consumer wait");
                    wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            Integer integer = list.removeFirst();
            size--;
            // 可能唤醒自己所以要用notifyall
            notifyAll();
            return integer;
        }
    
        public synchronized void producer(int i) {
            System.out.println(Thread.currentThread().getName());
            while (size >= max) {
                try {
                    System.out.println("producer wait");
                    wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            list.add(i);
            size++;
            notifyAll();
        }
    
    
        public static void main(String[] args) {
            A a = new A();
    
            for (int i = 0; i < 5; i++) {
                new Thread(() -> {
                    for (int j = 0; j < 100; j++) {
                        a.consumer();
                    }
                }, "consumer" + i).start();
            }
    
            for (int i = 0; i < 2; i++) {
                new Thread(() -> {
                    for (int j = 0; j < 100; j++) {
                        a.producer(j);
                    }
                }, "producer" + i).start();
            }
        }
    }
    
    
  • 相关阅读:
    我的程序优化尽量减少数据库连接操作
    dreamhappy博客索引
    一步一步实现网站的多语言版本
    spring入门基础
    discuz模版的学习
    第七次jsp作业
    第五次作业
    jsp第二次作业
    第六次作业
    jsp第六周作业
  • 原文地址:https://www.cnblogs.com/wilwei/p/11218492.html
Copyright © 2011-2022 走看看