我遇到了一个令人难以置信的奇怪现象。我目前正在用Java编写即时通讯程序,并且有一个变量来表示新用户是否已连接(属于单独的类)。这是有问题的代码在哪里对象ListenerThread extends Thread
:
boolean listenerThreadConnected = ServerDriver.getListenerThread().connected;
System.out.println("Whatever in here");
if(listenerThreadConnected){
...
System.out.println("In the if statement");
...
}
因此,此代码有效。当listenerThreadConnected = true
该if
语句执行并输出In the if statement
并执行if语句中的所有其他内容时。但是,除了注释掉之外,我没有更改任何其他代码,System.out.println("Whatever in here")
并且该if
语句未触发,也没有In the if statement
输出任何信号的迹象。我的代码如下所示:
boolean listenerThreadConnected = ServerDriver.getListenerThread().connected;
//System.out.println("Whatever in here");
if(listenerThreadConnected){
...
System.out.println("In the if statement");
...
}
我很困惑。这如何System.out.println
影响实际逻辑?我知道这个问题是开放性的,但是您有过类似的经历吗?在某些情况下,这都是while
循环的,而ListenerThread是并发运行的Thread。除了当前代码外,我似乎无法复制此结果。
[编辑]将System.out.println
a替换为aThread.sleep(1)
也似乎可行,因此这使我认为这是一个并发问题。
根本没有那么扩展,您肯定在多线程系统中并且您的应用程序获取了过时的boolean
值,在读取变量listenerThreadConnected时,需要确保内存可见性
如何:?
将此声明boolean listenerThreadConnected
为易失性,并且必须消除错误!
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句