手机版
你好,游客 登录 注册 搜索
背景:
阅读新闻

Java并发编程下变量可见行分析

[日期:2012-11-21] 来源:Linux社区  作者:zhongweijian [字体:大 中 小]

此时 volatile修饰词当然就派上用场了,volatile就是让变量的修改能够让该变量的值从主存中读取,当然更新了各个线程就都能看到了。

还有一种方式也可以达到上面的效果,就是使用synchronized同步,synchronized同步也能够让各个线程从主存中获取最新的值。

package com.mime; 
 
public class RaceCondition { 
//  private static volatile boolean done; 
 
    public static void main(final String[] args) throws InterruptedException { 
        new Thread(new Runnable() { 
            public void run() { 
                int i = 0; 
                while (!getFlag()) { 
                    i++; 
                } 
                System.out.println("Done!"); 
            } 
        }).start(); 
        System.out.println("OS: " + System.getProperty("os.name")); 
        Thread.sleep(2000); 
        setFlag(true); 
        System.out.println("flag done set to true"); 
    } 
     
    private static boolean done; 
    public static synchronized boolean getFlag() { return done; } 
    public static synchronized void setFlag(boolean flag) { done = flag; } 
} 

输出同样是:

OS: Linux 
flag done set to true 
Done! 

 

Simply put, it is the copying from local or working memory to main memory. 
A change made by one thread is guaranteed to be visible to another thread only if 
the writing thread crosses the memory barriera and then the reading thread crosses 
the memory barrier. synchronized and volatile keywords force that the changes are 
globally visible on a timely basis; these help cross the memory barrier—accidentally 
or intentionally. 
The changes are first made locally in the registers and caches and then cross the 
memory barrier as they are copied to the main memory. The sequence or ordering 
of these crossing is called happens-before—see “The Java Memory Model,” Appendix 
2, Web Resources, on page 255, and see Brian Goetz’s Java Concurrency in 
Practice [Goe06]. 
The write has to happens-before the read, meaning the writing thread has to cross 
the memory barrier before the reading thread does, for the change to be visible. 
Quite a few operations in the concurrency API implicitly cross the memory barrier: 
volatile, synchronized, methods on Thread such as start() and interrupt(), methods on Execu- 
torService, and some synchronization facilitators like CountDownLatch. 

linux
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款