volatile
volatile 关键字,使一个变量在多个线程间可见。
A B线程都用到一个变量,java默认是A线程中保留一份copy,这样如果B线程修改了该变量,则A线程未必知道。使用volatile关键字,会让所有线程都会读到变量的修改值。
在下面的代码中,running是存在于堆内存的t对象中。当线程t1开始运行的时候,会把running值从内存中读到t1线程的工作区,在运行过程中直接使用这个copy,并不会每次都去读取堆内存,这样,当主线程修改running的值之后,t1线程感知不到,所以不会停止运行。使用volatile,将会强制所有线程都去堆内存中读取running的值。
import java.util.concurrent.TimeUnit;
public class T01_HelloVolatile {
/*volatile*/ boolean running = true; //对比一下有无volatile的情况下,整个程序运行结果的区别
void m() {
System.out.println("m start");
while(running) {
}
System.out.println("m end!");
}
public static void main(String[] args) {
T01_HelloVolatile t = new T01_HelloVolatile();
new Thread(t::m, "t1").start();
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
t.running = false;
}
}
volatile 引用类型(包括数组)只能保证引用本身的可见性,不能保证内部字段的可见性
例子1:
import java.util.concurrent.TimeUnit;
public class T02_VolatileReference1 {
boolean running = true;
volatile static T02_VolatileReference1 T = new T02_VolatileReference1();
void m() {
System.out.println("m start");
while(running) {
try {
TimeUnit.MILLISECONDS.sleep(10);
System.out.println("running");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("m end!");
}
public static void main(String[] args) {
new Thread(T::m, "t1").start();
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
T.running = false;
System.out.println("set T.running = false");
}
}
例子2:
public class T03________VolatileReference2 {
private static class Data {
int a, b;
public Data(int a, int b) {
this.a = a;
this.b = b;
}
}
volatile static Data data;
public static void main(String[] args) {
Thread writer = new Thread(()->{
for (int i = 0; i < 10000; i++) {
data = new Data(i, i);
}
});
Thread reader = new Thread(()->{
while (data == null) {}
int x = data.a;
int y = data.b;
if(x != y) {
System.out.printf("a = %s, b=%s%n", x, y);
}
});
reader.start();
writer.start();
try {
reader.join();
writer.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("end");
}
}
volatile并不能保证多个线程共同修改running变量时所带来的不一致问题,也就是说volatile不能替代synchronized
例子:
import java.util.ArrayList;
import java.util.List;
public class T04_VolatileNotSync {
volatile int count = 0;
void m() {
for(int i=0; i<10000; i++) count++;
}
public static void main(String[] args) {
T04_VolatileNotSync t = new T04_VolatileNotSync();
List<Thread> threads = new ArrayList<Thread>();
for(int i=0; i<10; i++) {
threads.add(new Thread(t::m, "thread-"+i));
}
threads.forEach((o)->o.start());
threads.forEach((o)->{
try {
o.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
});
System.out.println(t.count);
}
}
使用synchronized解决上述问题,synchronized可以保证可见性和原子性,volatile只能保证可见性
import java.util.ArrayList;
import java.util.List;
public class T05_VolatileVsSync {
/*volatile*/ int count = 0;
synchronized void m() {
for (int i = 0; i < 10000; i++)
count++;
}
public static void main(String[] args) {
T05_VolatileVsSync t = new T05_VolatileVsSync();
List<Thread> threads = new ArrayList<>();
for (int i = 0; i < 10; i++) {
threads.add(new Thread(t::m, "thread-" + i));
}
threads.forEach((o) -> o.start());
threads.forEach((o) -> {
try {
o.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
});
System.out.println(t.count);
}
}
总结
- 保证线程可见性
- 缓存一致性原则
- 禁止指定重排序(CPU)
- 单例模式中的双重检查(double check)
- loadfence原语指令
- storefence原语指令