Java不遵循代码? [英] Java Does Not Follow Code?

查看:95
本文介绍了Java不遵循代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是我认为不遵循代码应该执行的代码片段:

Here is a snippet of the code I think does not follow what code should do:

public void updateTimeElapsed() {
    timeElapsedLabel.setText("Time elapsed: " + ((System.nanoTime() - time) / Math.pow(10, 9)));
}

public void updateTimeElapsedIndefinitely() {
    while (true) {
        //System.out.println("Hi");
        //TODO: Why this no work?
        if (start) { System.out.println("Shoulda'"); updateTimeElapsed(); }
    }
}

如果我发表评论

System.out.println("Hi")

代码显然不起作用。
如果我取消注释它,那就确实了!

The code apparently does not work. If I uncomment it, then it does!

注意:只要按's'开始游戏,
start就为真。
然而,该方法在开始时被调用,所以hi应该多次显示并且无限期地显示,直到我按下's'键。

Note: start is true as soon as you press 's' to start the game. However, the method is called in the beginning so "hi" should be displayed many times and indefinitely until I press the 's' key.

一张图片说千言万语,所以我会给你数百张图片(视频)来解释我的意思:
https://dl.dropbox.com/u/2792692/CodeWeird.ogv

A picture says a thousand words, so I'll give you hundreds of pictures (video) to explain what I mean: https://dl.dropbox.com/u/2792692/CodeWeird.ogv

https://dl.dropbox.com/u/2792692/CodeWeird.wmv

谁能告诉我发生了什么?

Can anyone tell me what is going on?

推荐答案

看起来像布尔 start 正在被另一个线程更新,但您没有将其声明为 volatile ,因此循环永远不会查看更新后的值。

Looks like the boolean start is being updated by another thread but you didn't declare it as volatile, so the loop never looks at the updated value.

通过添加println修复它只是JVM在获取本机系统对象时管理线程堆栈状态的方式的一个奇怪结果控制台打印机。解决方法是启动volatile和/或同步访问它。

"Fixing" it by adding the println is just a wierd consequence of the way JVM manages the thread's stack state when it goes to acquire the native system object for the console printer. The fix is to make start volatile and/or synchronize around accessing it.

SCCE:

从不打印:

public class Testit {

    public static void main(String[] args) {
        busted t = new busted();
        t.start();
        try {
        Thread.sleep(1000L);
        } catch (Exception e) {}
        t.startUpdating();

}

    public static class busted extends Thread {

        private boolean start = false;

        public void startUpdating() {
            start = true;
        }

        @Override
        public void run() {
            updateTimeElapsedIndefinitely();
        }

        public void updateTimeElapsedIndefinitely() {
            while (true) {
                if (start) {
                    System.out.println("Hello");
                }
            }
        }
    }
}

1秒后开始发送垃圾邮件Hello更改为:

Starts spamming Hello after 1 second by changing to this:

private volatile boolean start = false;

这篇关于Java不遵循代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆