volatile是一種輕量級鎖,被volatile關鍵字修飾的變量,在線程之間是可見的。即一個線程修改了這個變量的值,在另一個線程中能夠讀到這個修改後的值。
像我們之前所說的synchronize除了能讓線程之間互斥以外,還有一個非常大的作用就是辦證變量的可見性。
/**
* 保證可見性的前提
* <p>
* 多個線程拿到的是同一把鎖,否則是保證不了的。
*
* @author worker
*/
public class Demo {
private int a = 1;
public synchronized int getA() {
return a++;
}
public synchronized void setA(int a) {
try {
Thread.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
this.a = a;
}
public static void main(String[] args) {
Demo demo = new Demo();
demo.a = 10;
new Thread(new Runnable() {
@Override
public void run() {
System.out.println(demo.a);
}
}).start();
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("最終的結果爲:" + demo.getA());
}
}
用synchronize過於重量級
public class Demo2 {
public volatile boolean run = false;
public static void main(String[] args) {
Demo2 d = new Demo2();
new Thread(new Runnable() {
@Override
public void run() {
for (int i = 1; i <= 10; i++) {
System.err.println("執行了第 " + i + " 次");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
d.run = true;
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
while (!d.run) {
// 不執行
}
System.err.println("線程2執行了...");
}
}).start();
}
}