首页 > 其他 > 详细

延迟实例单例模式注意点

时间:2014-03-20 18:15:30      阅读:317      评论:0      收藏:0      [点我收藏+]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public class Singleton {
 
    private static volatile Singleton singleton = null;//volatile阻止JVM对指令执行顺序的优化,防止乱序执行导致导致返回的实例为半成品
 
    private void Singleton() {}
 
    public static Singleton getInstance() {
        if (singleton == null) {
            synchronized (Singleton.class) {
                if (singleton == null) {//双重检查,如果第二个线程进入不做检查会产生不同的实例
                    singleton = new Singleton();
                }
            }
        }
        return singleton;
    }
 
    public static void main(String[] args) {
        System.out.println(Singleton.getInstance() == Singleton.getInstance());
    }
}

  

延迟实例单例模式注意点,布布扣,bubuko.com

延迟实例单例模式注意点

原文:http://www.cnblogs.com/easylifesh/p/3614152.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!