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();
}
}