package com.peanut.singleton;
/**
* 多线程下正确的单例模式写法
* Created by peanut on 2016/4/25.
*/
public class SingletonDemo {
private SingletonDemo() {
}
//synchronized
private static SingletonDemo instance;
private synchronized static SingletonDemo getInstance() {
if (instance == null)
instance = new SingletonDemo();
return instance;
}
//2、volatile+双重检查锁定
private volatile static SingletonDemo instance1;
private static SingletonDemo getInstance1() {
if (instance1 == null) {
synchronized (SingletonDemo.class) {
if (instance1 == null) {
instance1 = new SingletonDemo();
}
}
}
return instance1;
}
//3、静态内部类实现
private static class SingletonHolder {
private static SingletonDemo instance2 = new SingletonDemo();
}
private static SingletonDemo getInstance2() {
return SingletonHolder.instance2;
}
}
多线程下单例模式的正确写法
最新推荐文章于 2022-04-30 21:06:11 发布