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();
            }
                
        }

    }

  • 相关阅读:
    Android学习—Shape
    Android学习—Application的作用
    用户管理
    DPKG命令与软件安装、APT
    Linux学习笔记
    C如何使用内存
    九九乘法表.py
    超市买苹果.py
    第一个程序python.py
    JavaScript一些备忘知识
  • 原文地址:https://www.cnblogs.com/wadmwz/p/7457125.html
Copyright © 2011-2022 走看看