volatile
共享变量+volitale
- 保证线程间的可见性
- 禁止指令重排
/*
一、boolean flag运行结果:
线程1 flag=false
【一直阻塞】
二、volatile boolean flag运行结果:
线程2 循环次数=71585922
线程2 over
线程1 flag=false
**/
public class T {
private static volatile boolean flag = true;
public static void main(String[] args) {
new Thread(() -> {
try {
//保证线程2 先与 线程1 执行
Thread.sleep(20);
flag = false;
System.out.println(Thread.currentThread().getName() + " flag=" + flag);
} catch (Exception e) {
}
}, "线程1").start();
new Thread(() -> {
try {
int counter = 0;
//boolean flag:线程2 一直阻塞状态,说明JIT底层优化了
//volatile boolean flag:线程间可见性,禁止JIT底层代码优化
while (flag) {
++counter;
}
System.out.println(Thread.currentThread().getName() + " 循环次数=" + counter);
} catch (Exception e) {
}
System.out.println(Thread.currentThread().getName() + " over");
}, "线程2").start();
}
}
指令重排
没测出效果o(╥﹏╥)o
import lombok.SneakyThrows;
public class T {
public static void main(String[] args) {
while (true) {
new Thread(() -> {
System.out.println(Singleton.getInstance());
}).start();
}
}
}
class Singleton {
private static /*volatile*/ Singleton singleton;
private Singleton() {
}
@SneakyThrows
public static Singleton getInstance() {
if (singleton == null) {
synchronized (Singleton.class) {
if (singleton == null) {
singleton = new Singleton();
}
}
}
return singleton;
}
}
借助jcstress工具压测,没成功o(╥﹏╥)o
<dependency>
<groupId>org.openjdk.jcstress</groupId>
<artifactId>jcstress-core</artifactId>
<version>0.3</version>
<scope>test</scope>
</dependency>