volatile修飾引用類型能否保證可見性似乎一直沒有一個定論显设,有的書中說僅能保證引用本身的可見性废封,下面用兩段代碼來驗(yàn)證:流程基本為一個線程死循環(huán)讀取某個引用類型的某個變量的值,另一個線程修改這個值十饥,觀察線程是否結(jié)束窟勃。
//volatile修飾類
public class TestVolatile implements Runnable{
class Foo {
boolean flag = true;
}
private volatile Foo foo = new Foo(); //
public void stop(){
foo.flag = false;
}
@Override
public void run() {
while (foo.flag){}
}
public static void main(String[] args) throws InterruptedException {
TestVolatile test = new TestVolatile();
Thread t = new Thread(test);
t.start();
Thread.sleep(1000);
test.stop();
}
}
//volatile修飾數(shù)組
public class TestVolatile2 implements Runnable{
private int len = 1024*1024;
volatile int[] arr = new int[len]; //
{
arr[len-1] = 1;
}
public void stop(){
arr[len-1] = 0;
}
@Override
public void run() {
while (arr[len-1] == 1){}
}
public static void main(String[] args) throws InterruptedException {
TestVolatile2 test = new TestVolatile2();
Thread t = new Thread(test);
t.start();
Thread.sleep(1000);
test.stop();
}
}
上面兩段代碼在有volatile字段的時候可觀察到程序停止運(yùn)行,沒有volatile字段的時候會一直運(yùn)行下去逗堵。