单例模式的三种写法
程序员文章站
2022-07-13 23:34:28
...
1、懒汉式
public class SingleDemo {
private static SingleDemo instance = null; //懒汉式
private SingleDemo(){
System.out.println(Thread.currentThread().getName()+"\t我是构造方法singleDemo");
}
public static SingleDemo getInstance(){
if(instance == null){
instance = new SingleDemo();
}
return instance;
}
public static void main(String[] args) {
System.out.println(SingleDemo.getInstance() == SingleDemo.getInstance());
System.out.println(SingleDemo.getInstance() == SingleDemo.getInstance());
// for(int i = 1 ; i <= 100 ; i++){
// new Thread(() -> {
// SingleDemo.getInstance();
// },String.valueOf(i)).start();
// }
}
}
2、饿汉式
public class EHanDemo {
private static EHanDemo instance =new EHanDemo(); //饿汉式
private EHanDemo(){}
public static EHanDemo getInstance(){
return instance;
}
}
3、双重检测锁模式
双重检测锁模式不一定线程安全,有指令重排的存在,加入volatile可以禁止指令重排
public class DoubleCheck { //双重检测锁
private static volatile DoubleCheck instance = null;
private DoubleCheck(){
System.out.println(Thread.currentThread().getName() + "\t我是构造方法SingletonDemo()");
}
public static DoubleCheck getInstance(){
if(instance == null){
synchronized (DoubleCheck.class){
if(instance == null){
instance = new DoubleCheck();
}
}
}
return instance;
}
public static void main(String[] args) {
for (int i = 0; i < 10 ; i++) {
new Thread(() -> {
DoubleCheck.getInstance();
},String.valueOf(i)).start();
}
}
}
上一篇: 单例模式的三种常见写法
下一篇: 单例模式的三种写法