随笔-95  评论-31  文章-10  trackbacks-0
 1/**
 2 * @author lx
 3 * 线程不安全的单例,试想两个线程都进入了if(singleton==null)块里这个时候会初始化两个对象,这只在第一次调用的时候会产生
 4 */

 5public class Unsafe_singleton {
 6
 7    private static Unsafe_singleton singleton;
 8
 9    private Unsafe_singleton() {
10    }

11
12    public static Unsafe_singleton getInstance() {
13        if (singleton == null{
14            singleton = new Unsafe_singleton();
15        }

16        return singleton;
17    }

18}

19public class Safe_singleton {
20     
21    private static Safe_singleton singleton;
22
23    private Safe_singleton() {
24    }

25
26    /**
27     * 这种写法,非常消耗性能,因为只是第一次进来的时候可能会产生多个实例的情况,后面多线程都不会再进行实例化,那么调用的时候会很降低性能
28     * @return
29     */

30    public static synchronized Safe_singleton getInstance() {
31        if (singleton == null{
32            singleton = new Safe_singleton();
33        }

34        return singleton;
35    }

36}

37/**
38 * @author lx
39 * 这种写法如果在创建和运行时的负担不太繁重,那么这种写法也可以保证多线程安全,每个线程进来都会new 创建此实例。
40 * 这种单例相对于每个线程来说确实是唯一的
41 */

42public class MoreSafe_singleton {
43        
44    private static MoreSafe_singleton singleton = new MoreSafe_singleton();
45    
46    public static MoreSafe_singleton getInstance(){
47        return singleton;
48    }

49}

50/**
51 * @author lx
52 * volatile 这个只在JDK1.5以上出现 它确保singleton变量被初始化时,多个线程正确地处理singleton变量
53 * 这种写法如果性能是关注的重点,那么可以大大减少getInstance()的时间消耗
54 */

55public class VerySafe_singleton {
56     
57    private volatile static VerySafe_singleton singleton;
58    private VerySafe_singleton(){}
59    
60    public static VerySafe_singleton getInstance(){    
61        if(singleton==null){
62            synchronized(VerySafe_singleton.class){    
63                if(singleton==null)//里面为何在加上判断是否为空?
64                    //因为试想如果有三个线程其中一个线程刚刚走出synchronized块,这个时候又进来一个线程,
65                    //如果不判断是否为空,这个又会实例一个变量那么就不是单例了
66                    singleton=new VerySafe_singleton();
67                }

68            }

69        }

70        return singleton;
71    }

72}
posted on 2010-09-02 15:44 朔望魔刃 阅读(355) 评论(1)  编辑  收藏 所属分类: 设计模式&&数据结构

评论:
# re: 再理解单例 2010-09-06 12:34 | xylz

只有注册用户登录后才能发表评论。


网站导航: