weixin_43110614 2022-02-26 20:48 采纳率: 50%
浏览 31
已结题

我这个是哪里不对,多线程学蒙了

这个多线程生产消费包子,我的生产完5个为什么还停留在p1线程,没搞懂,不是wait了么

我的解答思路和尝试过的方法

public class Demo {
    public static void main(String[] args)  {
       ProductThread p1 = new ProductThread(0);
       ProductThread c1 = new ProductThread(1);
       ProductThread c2 = new ProductThread(1);
       ProductThread c3 = new ProductThread(1);
       p1.start();
       c1.start();
       c2.start();
       c3.start();
    }
}

class ProductThread extends Thread{
    public static int num = 0;
    public static boolean flag = true;
    private int post;
    public ProductThread(int post) {
        this.post = post;
    }

    @Override
    public void run() {
        if(post==0){
            this.product();
        }else {
            this.consume();
        }
    }

    private synchronized void consume() {
        while(true){
            if(flag){
                try {
                    wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println(Thread.currentThread().getName()+"吃了一个包子,还剩"+(--num)+"个包子");
            if(num==0){
                flag=true;
                notifyAll();
            }
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    private synchronized void product(){
        while(true){
            if(!flag){
                try {
                    wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println("做了一个包子,还剩"+(++num)+"个包子");
            if(num==5){
                flag=false;
                notifyAll();
            }
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}


我想要达到的结果
  • 写回答

1条回答 默认 最新

  • 冰棍hfv 2022-02-26 23:58
    关注

    notifyAll()是唤醒正在等待此对象监视器锁的所有线程。这里没有唤醒成功的原因可能是持有的锁不同

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

问题事件

  • 系统已结题 3月7日
  • 已采纳回答 2月27日
  • 创建了问题 2月26日

悬赏问题

  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。