System.out.println行影响逻辑的执行

dsiegler19

我遇到了一个令人难以置信的奇怪现象。我目前正在用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 = trueif语句执行并输出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.printlna替换为aThread.sleep(1)也似乎可行,因此这使我认为这是一个并发问题。

ΦXocę웃Пepeúpatsu

根本没有那么扩展,您肯定在多线程系统中并且您的应用程序获取了过时的boolean值,在读取变量listenerThreadConnected时,需要确保内存可见性

如何:?

将此声明boolean listenerThreadConnected为易失性,并且必须消除错误!

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章