我遇到了一个令人难以置信的奇怪现象。我目前正在使用Java编写即时通讯程序,并且我有一个变量来表示新用户是否已连接(这是在单独的类中)。这是有问题的地方对象ListenerThread extends Thread
代码:System.out.println影响执行逻辑的线路
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是并发运行的线程。我似乎无法复制这个结果,除了在我目前的代码。
[编辑]更换System.out.println
有Thread.sleep(1)
也似乎工作,所以这使我觉得这是一种并发问题。
非常感谢。对于多线程和并发来说很新颖。 – dsiegler19