Threads和println()语句之间的关系 [英] Relationship between Threads and println() statements
问题描述
我尝试创建一些场景来演示跨线程共享变量时的可见性问题。我注意到在我测试的几乎所有情况下,如果在run()内部,我在使用共享变量的同一代码块中添加了System.out.println()语句,则无法生成可见性问题。我将提供一个示例:
I was trying to create a few scenarios to demonstrate visibility issues while sharing variable across threads. And I noticed that in almost all the cases I tested, if inside run() I added a System.out.println() statement in the same block of code where I am using the shared variable, the visibility issue is not producible. I will provide one example:
配置详细信息 - Oracle Java6 64位,Eclipse Juno SR 2
Configuration details - Oracle Java6 64bit, Eclipse Juno SR 2
-
1)具有可见性问题:
1)WITH VISIBILITY ISSUE:
public class NoVisibility_Demonstration extends Thread {
boolean keepRunning = true;
public static void main(String[] args) throws InterruptedException {
NoVisibility_Demonstration t = new NoVisibility_Demonstration();
t.start();
Thread.sleep(1000);
t.keepRunning = false;
System.out.println("keepRunning is false");
}
public void run() {
int x = 1;
while (keepRunning)
{
//System.out.println("If you uncomment this line, the code will work without the visibility issue");
x++;
}
System.out.println("x:"+x);
}
}
输出:线程保持无限运行
- 2)没有可见性问题:
上面的相同代码,带有未发布的println()运行中的声明()
输出:
...
如果您取消注释此行,代码将在没有可见性问题的情况下工作
If you uncomment this line, the code will work without the visibility issue
如果您取消注释此行,代码将无法使用可见性问题
If you uncomment this line, the code will work without the visibility issue
如果您取消注释此行,代码将在没有可见性问题的情况下工作
If you uncomment this line, the code will work without the visibility issue
x:19391
keepRunning为false
keepRunning is false
由于我在所有尝试的例子中都注意到了类似的行为,我想知道是否有在任何I / O操作之前由JVM进行的任何数据完整性检查。
Since I noticed similar behavior in all the examples I tried, I am wondering if there is any data integrity check by JVM before any I/O operation.
推荐答案
PrintWriter已同步
PrintWriter is synchronized
public void println(String x) {
synchronized(this) {
this.print(x);
this.newLine();
}
}
系统的两次连续调用主线程和第二个线程中的.out.println()
在两个线程之间创建同步顺序。这意味着代码将看到在释放监视器(退出同步方法)之前在主线程中发生的所有操作(在您的情况下是变量更新),在获取监视器之后在第二个线程中执行(输入synchronized方法) 。
Two sequential calls of System.out.println()
in main thread and in second thread create a synchronization order between two threads. That means that all actions (in your case it is variable update), that happened in main thread before releasing a monitor (exiting synchronized method) will be seen by the code, executed in second thread after it acquires a monitor (enter synchronized method).
简单来说,是的,调用 System.out.println()
进行同步。
In simple words, yes, calling System.out.println()
makes this synchronization.
这篇关于Threads和println()语句之间的关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!