[英]Threaded class variable not being set correctly
I have a threaded class shown below, which should terminate upon m_bExit
being set to false. 我有一个如下所示的线程类,该类应在m_bExit
设置为false时终止。 The boolean m_bMessageReceived
is set externally. 布尔值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();
}
}
The CommsTimeout
class is being initialised in another class... CommsTimeout
类正在另一个类中初始化...
m_threadCommsTimeout = new CommsTimeout();
... and m_bMessageReceived
is being set as so in another class every few miliseconds: ...并且每隔几毫秒就在另一个类中设置m_bMessageReceived
:
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. 我的问题是,即使在超时时间内将m_bMessageReceived
设置为true
,仍会到达// Do stuff
行。 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. 当将变量设置在另一个线程中时,不能保证您的线程会看到对m_bMessageReceived
的更改。 Try making m_bMessageReceived
volatile
. 尝试使m_bMessageReceived
volatile
。 This will ensure that your thread will see the most recent value of the variable. 这将确保您的线程将看到该变量的最新值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.