您的位置:首页 > 其它

多线程下单例模式的正确写法

2016-04-25 21:53 288 查看
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;
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息