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

    }

  • 相关阅读:
    InDesign 2022创建动态电子书和电子杂志
    如何在Mac上使用屏幕共享
    Mac终端程序背景如何设置为透明的?
    使用photoshop2021对有阴影的背光摄影照片进行调色修改
    Sketch如何实现背景局部模糊?
    苹果 macOS Monterey 12.3 开发者预览版 Beta 4 发布
    让Mac程序坞只显示正在运行的应用程序的方法
    Cornerstone 意外退出、打开闪退的解决办法
    windows下清理DNF缓存
    Centos7friewalld报错Failed to start firewalld dynamic firewall daemon
  • 原文地址:https://www.cnblogs.com/wadmwz/p/7457125.html
Copyright © 2020-2023  润新知