我有一个如下所示的线程类,它应该在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
行。我错过了什么?谢谢!
答案 0 :(得分:0)
这可能是一个可见性问题。当变量在另一个线程中设置时,无法保证您的线程会看到m_bMessageReceived
的更改。尝试制作m_bMessageReceived
volatile
。这将确保您的线程将看到变量的最新值。