shaokel 2019-06-11 17:40 采纳率: 95.2%
浏览 268
已采纳

请求大佬支援!!这个id是怎么获取数值的,馒头的那个类都没有给id赋值?

container.pop().id 是怎么获取数值的?谢谢在座的帮助!!!

package com.sxt.cooperation;

//协作模式:生产者消费者实现方式一:管程法
//借助缓冲区
public class CoTest01 {
    public static void main(String[] args) {
        SynContainer container = new SynContainer();
        new Productor(container).start();
        new Consumer(container).start();
    }
}

//生产者
class Productor extends Thread {
    SynContainer container;

    public Productor(SynContainer container) {
        super();
        this.container = container;
    }

    public void run() {
        // 生产
        for (int i = 0; i < 100; i++) {
            System.out.println("生产-->" + i + "个馒头");
            container.push(new Steamedbun(i));
        }
    }
}

//消费者
class Consumer extends Thread {
    SynContainer container;

    public Consumer(SynContainer container) {
        super();
        this.container = container;
    }

    public void run() {
        // 消费
        for (int i = 0; i < 100; i++) {
            System.out.println("消费-->" + container.pop().id + "个馒头");
        }
    }
}

//缓冲区
class SynContainer {
    Steamedbun buns[] = new Steamedbun[10];// 存储容器
    int count = 0;// 计数器

    // 存储生产
    public synchronized void push(Steamedbun bun) {
        //何时能生产   容器存在空间
        //不能生产   只能等待 
        if(count==buns.length) {
            try {
                this.wait();//线程堵塞   消费者通知     生成解除
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        //存在空间    可以生产 

        buns[count] = bun;
        count++;
        //存在数据   可以通知消费
        this.notifyAll();
    }

    // 获取消费
    public synchronized Steamedbun pop() {
        //何时消费  容器中是否存在数据
        //没有数据  只有等待
        if(count==0) {
            try {
                this.wait();//线程堵塞   生产者通知     消费解除
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        //存在数据即可消费 

        count--;
        Steamedbun bun = buns[count];// 拿最后一个
        this.notifyAll();//存在空间,可以唤醒对方生产
        return bun;
    }
}

//馒头
class Steamedbun {
    protected int id;

    public Steamedbun(int id) {
        super();
        this.id = id;
    }
}
  • 写回答

2条回答 默认 最新

  • 茂大叔 2019-06-11 18:02
    关注

    container.push(new Steamedbun(i));的时候不是给传了一个id进去么?这个是馒头的构造函数规定的嘛……构造一个馒头,就必须传一个id

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?