1.无volatile
/**volatile 有序性验证
* @author xueci
*
*/
public class TestSequence {
static int a,b;
static int x,y;
public static void main(String[] args) {
int i=0;
for (;;) {//死循环
a=0;b=0;
x=0;y=0;
i++;
Thread aThread1=new Thread(()->{
a=1;
x=b;
});
Thread bThread1=new Thread(new Runnable(){
@Override
public void run() {
b=1;
y=a;
}
});
aThread1.start();
bThread1.start();
try {
aThread1.join();
bThread1.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("第"+i+"次循环输出:"+"x="+x+";y="+y);
if(x==0 && y==0){
break;
}
}
}
}
结果:
2,加上volatile
public class TestSequence {
static volatile int a,b;
static int x,y;
public static void main(String[] args) {
int i=0;
for (;;) {//死循环
a=0;b=0;
x=0;y=0;
i++;
Thread aThread1=new Thread(()->{
//shortWait(3000);
a=1;
x=b;
});
Thread bThread1=new Thread(new Runnable(){
@Override
public void run() {
b=1;
y=a;
}
});
aThread1.start();
bThread1.start();
try {
aThread1.join();
bThread1.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("第"+i+"次循环输出:"+"x="+x+";y="+y);
if(x==0 && y==0){
break;
}
}
}
}
综上:
出现x=0;y=0;时说明线程一先执行x=b,线程二先执行y=a,后执行a=1,b=1,这时候出现出现指令重排,有序性无法保证。
给a,b加上volatile,一直运行不会停止,这时候不会出现指令重排,有序性得到保证,保证a,b先执行。