2013-02-13 84 views
0

我刚刚接触volatile变量,但是我正在阅读一篇文章,其中指出2)在某些情况下,如可见性,易变变量可用作实现Java同步的另一种方式。使用volatile变量保证所有读取器线程在写入操作完成后都会看到volatile变量的更新值,而不使用volatile关键字不同的读取器线程可能会看到不同的值。关于volatile变量的使用

我请求你们可以请你给我看一个小型的Java程序,所以在技术上也是很明显的。

我的理解是... 易变意味着每个线程访问该变量将拥有自己的私人副本,它与原来的一样。但是如果线程要改变该私人副本,那么原来的将不会得到体现。

public class Test1 { 
    volatile int i=0,j=0; 
    public void add1() 
      { 
      i++; 
      j++; 
     } 
    public void printing(){ 
     System.out.println("i=="+i+ "j=="+j); 
    } 

    public static void main(String[] args) { 
     Test1 t1=new Test1(); 
     Test1 t2=new Test1(); 
     t1.add1();//for t1 ,i=1,j=1 
     t2.printing();//for t2 value of i and j is still,i=0,j=0 
     t1.printing();//prints the value of i and j for t1,i.e i=1,j=1 
     t2.add1();////for t2 value of i and j is changed to i=1;j=1 
     t2.printing();//prints the value of i and j for t2i=1;j=1 
    } 

} 

我请求你们能请你告诉挥发功能的小程序,所以在技术上也很清楚,我

回答

1

视为您已阅读担保的知名度,但不保证原子volatile变量 - 另一个线程安全的重要方面。我会尝试用一个例子

public class Counter { 
    private volatile int counter; 

    public int increment() { 
     System.out.println("Counter:"+counter); // reading always gives the correct value 
     return counter++; // atomicity isn't guaranteed, this will eventually lead to skew/error in the expected value of counter. 
    } 

    public int decrement() { 
     System.out.println("Counter:"+counter); 
     return counter++; 
    } 
} 

在这个例子说明,你可以看到,读操作将永远给计数器的正确值在某个时刻,但原子操作(如计算一个条件,做根据读取值进行读写)线程安全性无法保证。

有关更多详细信息,请参阅this答案。

volatile意味着每个线程访问的变量将拥有自己的私人 副本是一样的原始one.But如果线程会 改变这种专用副本,那么原来的不会得到反映。

我不知道我理解你正确,但挥发性领域意味着他们正在阅读和所有线程访问主存储器写 - 有变量没有线程特定副本(缓存)。

JLS从,

中的字段可被声明挥发性的,在这种情况下,Java内存模型 确保所有线程看到用于可变

一致的值