会员可以在此提问,百战程序员老师有问必答
对大家有帮助的问答会被标记为“推荐”
看完课程过来浏览一下别人提的问题,会帮你学得更全面
截止目前,同学们一共提了 132450个问题
JAVA 全系列/第十八阶段:亿级高并发电商项目_架构/编码(旧)/电商:基于RPC软件模型使用PageHelper实现用户商品查询功能 18948楼
JAVA 全系列/第五阶段:JavaWeb开发/Servlet技术详解 18949楼
Python 全系列/ 第十四阶段:自动化操作办公软件、邮件、定时任务等/办公自动化 18951楼
Python 全系列/第一阶段:Python入门/编程基本概念 18953楼

老师,同步代码块中 wait()方法及 notify() 方法是用 this 对象调用的,那这个对象到底是哪个类下的对象?是 缓冲区 BufferZone 类下实例化的对象嘛?

// 馒头类
class SteamBread {
    private int id;

    public SteamBread(int id) {
        this.id = id;
    }

    public int getId() {
        return this.id;
    }
}

// 缓冲区类
class BufferZone {
    // 存放馒头的盒子
    private SteamBread[] sb = new SteamBread[10];
    // 定义操作盒子的索引
    private int index;

    // 生产者方法馒头
    public synchronized void put(SteamBread steamBread) {
        while (this.index >= this.sb.length) {
            try {
                this.wait();   // this 引用当前类的实例,所以对应的对象为 BufferZone 类下实例化的对象 bz
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        this.notify();
        this.sb[this.index] = steamBread;
        this.index++;
    }

    // 取馒头
    public synchronized SteamBread take() {
        while (this.index == 0) {
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        this.notify();
        this.index--;
        return this.sb[this.index];
    }
}

// 生产者线程类
class ProducerThread extends Thread {
    private BufferZone bz;

    public ProducerThread(BufferZone bz) {
        this.bz = bz;
    }

    @Override
    public void run() {
        for (int i = 0; i < 10; ++i) {
            System.out.println("生产馒头:" + i);
            SteamBread sb = new SteamBread(i);
            this.bz.put(sb);
        }
    }
}

// 消费者线程类
class ConsumerThread extends Thread {
    private BufferZone bz;

    public ConsumerThread(BufferZone bz) {
        this.bz = bz;
    }

    @Override
    public void run() {
        for (int i = 0; i < 10; ++i) {
            SteamBread sb = this.bz.take();
            System.out.println("消费馒头:" + i);
        }
    }
}


// 测试生产者消费者模式
public class ProducerConsumerModel {
    public static void main(String[] args) {
        BufferZone bz = new BufferZone();
        new ProducerThread(bz).start();
        new ConsumerThread(bz).start();
    }

}


JAVA 全系列/第二阶段:JAVA 基础深化和提高/多线程技术(旧) 18955楼
JAVA 全系列/第一阶段:JAVA 快速入门/控制语句、方法、递归算法 18958楼
Python 全系列/第二阶段:Python 深入与提高/GUI编程(隐藏) 18960楼

课程分类

百战程序员微信公众号

百战程序员微信小程序

©2014-2025百战汇智(北京)科技有限公司 All Rights Reserved 北京亦庄经济开发区科创十四街 赛蒂国际工业园
网站维护:百战汇智(北京)科技有限公司
京公网安备 11011402011233号    京ICP备18060230号-3    营业执照    经营许可证:京B2-20212637