奇怪的嵌套 if 语句执行

Weird nested-if statement execution

我在 Java 中编写的一些代码遇到了这个有趣的问题。我正在使用 jdk-17.0.1 在最新版本的 eclipse 中执行此代码。该代码的目的是每隔几毫秒截取一次我的屏幕截图,但前提是 运行 为真。一开始,运行 是错误的。我可以通过按某个键来设置 运行 为真。这是代码

        double timePerTick = 1_000_000_000/fps;
        double delta = 0;
        long now;
        long lastTime = System.nanoTime();
        while (true) {
            now = System.nanoTime();
            delta+= (now-lastTime)/timePerTick;
            lastTime = now;
            if (delta >= 1) {
                //for some reason code only works if this print statement here
                //System.out.println("WOWEE");
                if (running) {
                    //Create rectangle screen-capture around cursor
                    BufferedImage image = robot.createScreenCapture(new Rectangle(0,0, width, height));
                    try {
                        output.write(("Capture taken \n").getBytes());
                        System.out.println("WRITTEN!");
                    } catch (IOException e1) {
                        // TODO Auto-generated catch block
                        System.out.println("BRUH!");
                        e1.printStackTrace();
                    }
                }
                delta--;
            }
        }       

问题是 if (运行) 语句永远不会运行,即使 运行 为真。但是,当我取消注释 if(delta) 代码后的 System.out.println 语句时,它运行得非常好。像这样:

        double timePerTick = 1_000_000_000/fps;
        double delta = 0;
        long now;
        long lastTime = System.nanoTime();
        while (true) {
            now = System.nanoTime();
            delta+= (now-lastTime)/timePerTick;
            lastTime = now;
            if (delta >= 1) {
                //for some reason code only works if this print statement here
                System.out.println("WOWEE");
                if (running) {
                    //Create rectangle screen-capture around cursor
                    BufferedImage image = robot.createScreenCapture(new Rectangle(0,0, width, height));
                    try {
                        output.write(("Capture taken \n").getBytes());
                        System.out.println("WRITTEN!");
                    } catch (IOException e1) {
                        // TODO Auto-generated catch block
                        System.out.println("BRUH!");
                        e1.printStackTrace();
                    }
                }
                delta--;
            }
        }       

在第一个代码中,没有打印任何内容,但在第二个代码中,WOWEE 被一遍又一遍地打印出来。顺便说一句,如果 运行 一开始就为真,那么这两个代码都可以正常工作。但是,如果您从 运行 = false 切换到 运行 = true,则第一个代码不会打印任何内容,但第二个代码会从不打印任何内容变为打印 WOWEE。这有什么原因吗?

顺便说一句,如果需要的话,输出是一个 FileOutputStream 实例。

user16320675 在评论中找到了我的问题的答案,但出于某种原因他们删除了评论。我等着看他们会不会回来,但他们没有。所以,我会post他们给我的资料。我的程序没有运行的原因是因为变量“运行”被多个线程访问,一个线程是主线程,另一个线程是监视键盘输入的线程。当一块内存被多个线程访问时,您必须将其声明为“volatile”以确保同步问题不会发生。像这样

public static volatile boolean running;

这里有更多信息https://www.baeldung.com/java-volatile