用双端检锁机制不能保证线程安全,原因是存在指令重排。
/**
* @program: mybatis
* @description:
* @author: Miller.FAN
* @create: 2019-11-11 17:49
**/
public class SingletonDome {
private static SingletonDome instance = null;
private SingletonDome() {
System.out.println(Thread.currentThread().getName() + "/t 我是构造方法SingletonDome");
}
//DLC 双端检锁机制
public static SingletonDome getInstance() {
if(instance == null) {
synchronized (SingletonDome.class) {
if(instance == null) {
instance = new SingletonDome();
}
}
}
return instance;
}
public static void main(String[] args) {
for (int i = 0; i < 10 ; i++) {
new Thread( () -> {
SingletonDome.getInstance();
},String.valueOf(i)).start();
}
}
}
2、优化手段
/**
* @program: mybatis
* @description:
* @author: Miller.FAN
* @create: 2019-11-11 17:49
**/
public class SingletonDome {
//加volatile,禁止指令重排
private static volatile SingletonDome instance = null;
private SingletonDome() {
System.out.println(Thread.currentThread().getName() + "/t 我是构造方法SingletonDome");
}
//DLC 双端检锁机制
public static SingletonDome getInstance() {
if(instance == null) {
synchronized (SingletonDome.class) {
if(instance == null) {
instance = new SingletonDome();
}
}
}
return instance;
}
public static void main(String[] args) {
for (int i = 0; i < 10 ; i++) {
new Thread( () -> {
SingletonDome.getInstance();
},String.valueOf(i)).start();
}
}
}