Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/multithreading/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 影响逻辑执行的System.out.println行_Java_Multithreading_If Statement_Boolean Logic_System.out - Fatal编程技术网

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

Java 影响逻辑执行的System.out.println行,java,multithreading,if-statement,boolean-logic,system.out,Java,Multithreading,If Statement,Boolean Logic,System.out,我遇到了一个不可思议的奇怪现象。我目前正在用Java编写一个instant messenger程序,我有一个变量来表示新用户是否已连接(这在一个单独的类中)。下面是有问题的代码,其中对象ListenerThread扩展了Thread: boolean listenerThreadConnected = ServerDriver.getListenerThread().connected; System.out.println("Whatever in here"); if(listenerThr

我遇到了一个不可思议的奇怪现象。我目前正在用Java编写一个instant messenger程序,我有一个变量来表示新用户是否已连接(这在一个单独的类中)。下面是有问题的代码,其中对象
ListenerThread扩展了Thread

boolean listenerThreadConnected = ServerDriver.getListenerThread().connected;
System.out.println("Whatever in here");
if(listenerThreadConnected){
    ...
    System.out.println("In the if statement");
    ...
}
所以,这个代码是有效的。当
listenerThreadConnected=true
时,执行
if
语句,在if语句中输出
,并在if语句中执行所有其他操作。但是,除了注释掉
System.out.println(“此处的任何内容”)
if
语句没有触发,并且if语句中没有输出
的迹象之外,我没有更改任何其他代码。我的代码如下所示:

boolean listenerThreadConnected = ServerDriver.getListenerThread().connected;
//System.out.println("Whatever in here");
if(listenerThreadConnected){
    ...
    System.out.println("In the if statement");
    ...
}
我很困惑。这个
System.out.println
如何影响实际逻辑?我知道这个问题非常开放,但你有过类似的经历吗?对于某些上下文,这都在
中,而
循环和ListenerThread是一个并发运行的线程。除了在当前代码中,我似乎无法复制此结果


[EDIT]
线程替换
系统.out.println
。睡眠(1)
似乎也能起作用,因此我认为这是一个并发问题

一点也不过分,你肯定是在一个多线程系统中,你的应用程序得到了一个过时的
boolean
值,你需要确保在读取变量listenerThreadConnected

如何:?


将此
布尔listenerThreadConnected
声明为volatile,错误必须消失

一点也不过分,你肯定是在一个多线程系统中,你的应用程序得到了一个过时的
boolean
值,你需要确保在读取变量listenerThreadConnected

如何:?


将此
布尔listenerThreadConnected
声明为volatile,错误必须消失

请注意,
System.out.println
通常被实现为
synchronized
(即使这没有文档记录),以便您不会得到两个线程交错的输出

执行该语句的效果是使变量的更新对执行同步方法的线程可见(这是一种“发生在”之前的关系)

通过删除
System.out.println
调用,可以删除此行为,因此可能会看到过时的变量


As@Xoce웃Пepeúpa说,将变量
设置为volatile
,或执行其他操作以确保内存可见性(例如,将其更改为
原子布尔值
)。

请注意,
System.out.println
通常被实现为
同步的
(尽管没有文档记录),为了不得到两个线程交错的输出

执行该语句的效果是使变量的更新对执行同步方法的线程可见(这是一种“发生在”之前的关系)

通过删除
System.out.println
调用,可以删除此行为,因此可能会看到过时的变量


As@Xoce웃Пepeúpa说,将变量
设置为volatile
,或执行其他操作以确保内存可见性(例如,将其更改为
原子布尔值
)。

非常感谢。对于多线程和并发来说,这是一个非常新的概念。非常感谢。对于多线程和并发性来说,这是一个全新的概念。