zoukankan      html  css  js  c++  java
  • Java多线程之生产者消费者

    生产者和消费者的实例:

    商品类:
    /**
     * 商品类
     *
     */
    public class Goods {
        final int MAX_NUMBER = 30; // 最大数量
        final int MIN_NUMBER = 0; // 最小数量
        private int number;
        public Goods(int number) {
            super();
            this.number = number;
        }
        public synchronized int getNumber() {
            return number;
        }
        // 添加
        public  void addNumber() throws InterruptedException{
            if(number >= MAX_NUMBER){
                wait();
            }
            synchronized(this){ // 同步代码块
                this.number = number + 1;
                System.out.println("生产者生产商品,商品数为:" + number);
            }  
            notifyAll();
        }
        // 减少
        public  void sumNumber() throws InterruptedException{
            if(number <= MIN_NUMBER){
                wait();
            }
            synchronized(this){
                this.number = number - 1;
                System.out.println("消费者消费商品,商品数为:" + number);
            }
            notifyAll();
        }
    }

    测试类:

    package book_14.synch;

    public class Test {
        
        public static void main(String[] args) {
            // 创建对象
            Goods good = new Goods(20); // 开始的商品数量设为20
            
            while(true){
                // 生产者
                Runnable r1 = () ->{
                    try {
                        while(true){
                            good.addNumber();
                            //Thread.sleep(10);
                        }
                    } catch (Exception e) {
                        // TODO: handle exception
                    }
                };
                Thread t1 = new Thread(r1);
                t1.start();
                // 消费者
                Runnable r2 = () ->{
                    try {
                        while(true){
                            good.sumNumber();
                            //Thread.sleep(10);
                        }
                    } catch (Exception e) {
                        // TODO: handle exception
                    }
                };
                Thread t2 = new Thread(r2);
                t2.start();
            }
                
        }

    }

  • 相关阅读:
    Codeforces Round #696 (Div. 2) A
    软件体系结构期末复习
    LINUX 下配置 redis
    2020-09-30 刷题记录
    2020-09-29 刷题记录
    Codeforces Round #673 (Div. 2) A
    2020-09-26 刷题记录
    2020-09-25 刷题记录
    C++ 类虚函数实现原理的验证(指向包含类虚函数地址的数组的指针)
    Saleae8 与 SaleaeLogic、PulseView上位机的使用
  • 原文地址:https://www.cnblogs.com/wadmwz/p/7457125.html
Copyright © 2011-2022 走看看