未正确设置线程类变量

时间:2016-12-08 13:29:17

标签: java android multithreading volatile

我有一个如下所示的线程类,它应该在m_bExit设置为false时终止。布尔m_bMessageReceived在外部设置。

public class CommsTimeout extends Thread {

    public static boolean m_bMessageReceived = false;
    public volatile boolean m_bExit = false;
    private static long m_nStartTime;

    public void run() {

        while (!m_bExit) {
            while ((System.currentTimeMillis() < (m_nStartTime + Constants.PERIOD))) {
                // Wait...
            }
            if (!m_bMessageReceived) {
                // Do stuff.
            }

            m_bMessageReceived = false;
        }
    }

    public CommsTimeout() {

        // Reset flags.
        m_bMessageReceived = false;
        m_bExit = false;
        m_nStartTime = System.currentTimeMillis();
        this.start();
    }
}

CommsTimeout类正在另一个类中初始化......

m_threadCommsTimeout = new CommsTimeout();

...并且m_bMessageReceived每隔几毫秒在另一个类中设置如此:

CommsTimeout.m_bMessageReceived = true;

我的问题是,即使m_bMessageReceived在超时期限内设置为true,仍然会到达// Do stuff行。我错过了什么?谢谢!

1 个答案:

答案 0 :(得分:0)

这可能是一个可见性问题。当变量在另一个线程中设置时,无法保证您的线程会看到m_bMessageReceived的更改。尝试制作m_bMessageReceived volatile。这将确保您的线程将看到变量的最新值。