java设计模式之--线程安全的单例模式

1、线程安全的单例模式--懒汉式+volatile+sysnchronized+双重检查

2、上代码:

public class Test2 {

//volatile修饰:防止指令重排序导致值改变
private static volatile Test2 INSTANSE;

private Test2(){}

public static Test2 getInstance() {
//双重检查
if (null == INSTANSE) {
//加锁
synchronized (Test2.class) {
if (null == INSTANSE) {
INSTANSE = new Test2();
}
}
}
return INSTANSE;
}
}
posted @ 2020-04-21 22:10  水能载舟亦能喝  阅读(93)  评论(0编辑  收藏  举报