我刚接触易失性变量,但我正在阅读一篇文章,其中指出2)易失性变量在某些情况下可以用作Java中实现同步的另一种方式,比如可见性。使用易失性变量可以保证所有的读线程在写操作完成后都能看到易失性变量的更新值,如果不使用易失性关键字,不同的读取器线程会看到不同的值。
我请求你们能不能给我看一个小java程序,所以技术上对我来说也是很清楚的。
我的理解是..。易失性意味着每个线程访问变量都将拥有自己的私有副本,这与原始one.But相同。如果线程要更改私有副本,则原始副本将不会被反映。
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
}
} 我请求你们能不能展示一个易失性功能的小程序,所以从技术上来说我也很清楚
发布于 2013-02-13 13:52:53
您已经读过的易失性变量可以保证可见性,但不能保证原子性-线程安全的另一个重要方面。我将试着用一个例子来解释。
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++;
}
}在该示例中,您可以看到,读取操作将始终在某个时刻给出正确的counter值,但是原子操作(如评估条件并执行某项操作,以及基于读取的值进行读写)线程安全性不能得到保证。
您可以参考this answer了解更多详细信息。
易失性意味着每个线程访问变量都将拥有自己的私有副本,这与原始one.But相同。如果线程要更改该私有副本,则原始副本将不会得到反映。
我不确定我是否正确理解了您的意思,但易失性字段意味着它们是从所有线程可访问的主内存中读取和写入的-没有线程特定的变量副本(缓存)。
来自JLS,
Java字段可以声明为易失性,在这种情况下,
内存模型确保所有线程都看到变量
的一致值
https://stackoverflow.com/questions/14847187
复制相似问题