System.out.println的可见性问题?

贴出代码:

public class VisibilityDemo {
public static void main(String[] args) throws InterruptedException {
VisibilityTest v = new VisibilityTest();
v.start();
Thread.sleep(1000);
v.stoplt();
Thread.sleep(2000);
System.out.println(“finish main”);
System.out.println(v.getStop());
}

}

class VisibilityTest extends Thread {
private boolean stop;

@Override
public void run() {
	// TODO Auto-generated method stub
	long i = 0;
	while (!stop) {
		i++;

// System.out.println(“i=”+i);
}
System.out.println(“finish loop,i=” + i);
}

public void stoplt() {
	stop = true;
}

public boolean getStop() {
	return stop;
}

}

在main线程中将stop置为true。
运行结果为:
System.out.println的可见性问题?
发现循环并没有停止。

放开i++之后的注释 System.out.println(“i=”+i);

运行结果为:
System.out.println的可见性问题?
发现循环停止了。

这是为什么呢?
首先说说可见性,主线程把stop置为true时,会在不定时刻把值刷入主存中去;而Thread线程不断的从工作内存中拿值,stop依旧为false,致使while循环无法跳出。
stop加volatile关键字
对stop加volatile关键字能解决这个问题,因为volatile的作用就是能立即将工作内存修改后的值刷入主内存,并破坏其他线程工作内存中该值的缓存让它们必须从主内存中重新读取,保证了可见性。
不加volatile的情况下,通过System.out.println方法为什么也能退出while循环?
System.out.println的可见性问题?System.out.println的可见性问题?
因为print方法加了synchronized关键字(当然println也加了,换行操作也会持有锁)
而synchronized方法也是能保证了该同步块中的变量的可见性的,所以下次stop从主存中读出false就跳出了while。
这里记录一下synchronized做的操作:
1、获得同步锁;
2、清空工作内存;
3、从主内存拷贝对象副本到工作内存;
4、执行代码(计算或者输出等);
5、刷新主内存数据;
6、释放同步锁。

PS:第一次刷博客,见笑。。。