首页 > 解决方案 > System.out.println("") 改变程序的行为

问题描述

我有以下代码:

        boolean running = true;
        while (running) {
            MathStackJPanel focused = Main.frame.mainPanel.focused;
            //System.out.print("");
            if (focused != null) {
                Point p = focused.getMousePosition();
                ExpressionComponent ep = focused.getUnderPoint(p);
            }
        }

focused.getUnderPoint(p)应该打印一些东西(用于调试)但没有。一旦我取消注释System.out.print(""),代码就会按预期工作,并且我会看到控制台中打印的内容(来自focused.getUnderPoint(p))。为什么那条应该什么都不做的简单行会完全修改我的代码的行为?另外,我可以说 while 循环内的代码根本没有运行,因为System.out.print("")在某些情况下,当我取消注释时,会抛出异常(如预期的那样)。

java是否优化了我的while循环,即使它不应该?

有人要求一个更好的例子:

    public static Object b = null;

    public static void a() {
        System.out.println("OK");
    }

    public static void main(String[] args) {
        Thread thread = new Thread(() -> {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            b = 4;
        });

        thread.start();

        while (true) {
            //System.out.print("");
            if (b != null) {
                a();
            }
        }
    }

取消注释该行以使其工作(打印正常)

标签: javawhile-loop

解决方案


推荐阅读