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 蓝桥oj3931,请问我错在哪里
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染