m0_60329578 2021-12-15 19:17 采纳率: 66.7%
浏览 77
已结题

java中Debug 与 测试类运行结果不同

今天做了一个案例,生产者与消费者
public class BoxDemo {
    public static void main(String[] args) {
        Box b = new Box();

        Producer p = new Producer(b);

        Customer c = new Customer(b);

        Thread t1 = new Thread(p);
        Thread t2 = new Thread(c);


        t1.start();
        t2.start();

    }
}
public class Box {
    private int milk;
    private boolean state = false;

    public synchronized void put(int milk) {
        this.milk = milk;
        if (state) {
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }
        System.out.println("送奶工将第" + this.milk + "瓶奶放入奶箱");
        state = true;
        notifyAll();
    }

    public synchronized void get() {
        if (!state) {
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("用户拿到第" + this.milk + "瓶奶");
        state = false;
         notifyAll();
    }
public class Customer implements Runnable {
    private Box b;

    public Customer(Box b) {
        this.b = b;
    }

    @Override
    public void run() {
        while (true) {
            b.get();
        }
    }
}


public class Producer implements Runnable {
    private Box b;

    public Producer(Box b) {
        this.b = b;
    }


    @Override
    public void run() {
        for (int i = 1; i <= 5; i++) {
            b.put(i);
        }
    }
}

运行结果及与Debug 结果不同

img

我想要达到的结果

Debug 的结果才是我想要的结果 找了半天没找到原因
求解答

  • 写回答

2条回答 默认 最新

  • 五一编程 2021-12-15 19:33
    关注

    应该是多线程没有处理好导致的,一半debug和release除了优化参数不一样外,都是一样的,因为debug加入了许多调试符号,所以执行可能会慢一点,结果正常,
    release执行的快些,所以结果就不对了,一般都是多线程导致的

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

报告相同问题?

问题事件

  • 系统已结题 12月23日
  • 已采纳回答 12月15日
  • 创建了问题 12月15日

悬赏问题

  • ¥15 linux驱动,linux应用,多线程
  • ¥20 我要一个分身加定位两个功能的安卓app
  • ¥15 基于FOC驱动器,如何实现卡丁车下坡无阻力的遛坡的效果
  • ¥15 IAR程序莫名变量多重定义
  • ¥15 (标签-UDP|关键词-client)
  • ¥15 关于库卡officelite无法与虚拟机通讯的问题
  • ¥15 目标检测项目无法读取视频
  • ¥15 GEO datasets中基因芯片数据仅仅提供了normalized signal如何进行差异分析
  • ¥100 求采集电商背景音乐的方法
  • ¥15 数学建模竞赛求指导帮助