简体   繁体   中英

Threaded class variable not being set correctly

I have a threaded class shown below, which should terminate upon m_bExit being set to false. The boolean m_bMessageReceived is set externally.

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();
    }
}

The CommsTimeout class is being initialised in another class...

m_threadCommsTimeout = new CommsTimeout();

... and m_bMessageReceived is being set as so in another class every few miliseconds:

CommsTimeout.m_bMessageReceived = true;

My problem is that even though m_bMessageReceived is being set to true within the timeout period, the // Do stuff line is still being reached. What have I missed? Thanks!

This may be a visibility issue. There is no guarantee that your thread will see the change to m_bMessageReceived when the variable is set in a different thread. Try making m_bMessageReceived volatile . This will ensure that your thread will see the most recent value of the variable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM