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先執行。