单例模式-DoubleCheck

 1 /**
 2  * 单例模式-DoubleCheck
 3  */
 4 public class SingletonTest06{
 5     public static void main(String[] args) {
 6         Singleton instanceOne = Singleton.getInstance();
 7         Singleton instanceTwo = Singleton.getInstance();
 8         // out: true
 9         System.out.println(instanceOne == instanceTwo);
10     }
11 }
12 
13 /**
14  * DoubleCheck
15  */
16 class Singleton {
17     private static volatile Singleton instance;
18 
19     private Singleton() {
20 
21     }
22 
23     /**
24      * 提供一个静态的公有方法,加入双重检查代码25      *     解决线程安全问题,同时解决懒加载问题
26      */
27     public static Singleton getInstance() {
28         if (instance == null) {
29             synchronized (Singleton.class) {
30                 if (instance == null) {
31                     instance = new Singleton();
32                 }
33             }
34         }
35         return instance;
36     }
37 }

DoubleCheck

优缺点说明:

1) DoubleCheck概念是过线程开发中常用到的,如代码所示,我们进行了两次 if (instance == null) 检查,这样就可以保证线程安全了。

2) 实例化只执行一次,后面再次访问时,直接人return实例化对象,也避免了反复进行方法同步。

3) 线程安全;延迟加载;效率较高

4) 在实际开发中,推荐使用这种单例设计模式

posted @ 2020-10-31 10:04  树树树  阅读(657)  评论(0)    收藏  举报