1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | public class ThreadSafeCache { int result; /** * 用synchronized修饰就有可见性,不修饰没有可见性 */ public int getResult() { return result; } public void setResult( int result) { this .result = result; } public static void main(String[] args) throws InterruptedException { ThreadSafeCache threadSafeCache = new ThreadSafeCache(); for ( int i = 0 ; i < 8 ; i++) { new Thread(() -> { int x = 0 ; while (threadSafeCache.getResult() < 100 ) { x++; //System.out.println();//加上有可见性,不加没有可见性 } System.out.println(x); }).start(); } Thread.sleep( 1000 ); threadSafeCache.setResult( 200 ); } } |
对于这段代码,我有两个问题:
问题一:
为什么加上System.out.println(),就有可见性,程序就可以终止?不加,就无法终止
问题二:
在不加System.out.println()的情况下,在getResult()方法加上synchronized就有可见性,程序就可以终止,这是为什么呢?按理说读取值result,和线程安不安全应该说没有关系呀,又不是修改值
我的思考:
我怀疑和synchronized有关,毕竟System.out.println()也加了synchronized关键字。我在网上找到了如下解释:
请老师解答一下我心中的疑惑