2013-02-13 85 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內存模型 確保所有線程看到用於可變

一致的值