public class VolatileFeaturesExample { volatile long vl = 0L; public void set(long l) { vl = l; } public void getAndIncrement() { vl ;// 复合(多个)volatile变量的读/写 } public long get() { return vl;// 单个volatile变量的读 } }
class VolatileFeaturesExample1 { long vl = 0L; public synchronized void set(long l) { vl = l; } public synchronized long get() { return vl; } public void getAndIncrement() { long temp = get(); temp = 1L; set(temp); } }
public class VolatileExample { int a=0; volatile boolean flag=false; public void writer(){ a=1; //1 flag=true;//2 } public void reader(){ if(flag){//3 int i=a;//4 } } }
public class VolatileBarrierExample { int a; volatile int v1 = 1; volatile int v2 = 2; void readAndWrite() { int i = v1;// 第一个volatile读 int j = v2;// 第二个volatile读 a = i j;// 普通写 v1 = i 1;// 第一个volatile写 v2 = j * 2;// 第二个volatile写 } }
__asm__ volatile ("lock; addl $0,0(%%rsp)" : : : "cc", "memory");