单例模式-线程安全懒汉式

 1 /**
 2  * 单例模式-线程安全懒汉式
 3  */
 4 public class SingletonTest04 {
 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 class Singleton {
15 
16     /**
17      * 1.构造器初始化,外部不能new
18      */
19     private Singleton() {
20 
21     }
22 
23     /**
24      * 2.本类内部私有化变量。
25      */
26     private static Singleton instance;
27 
28     /**
29      * 3.提供一个公有的静态方法,加入同步处理的代码,解决线程安全问题
30      */
31     public static synchronized Singleton getInstance() {
32         if(instance == null) {
33             instance = new Singleton();
34         }
35         return instance;
36     }
37 
38 }

懒汉式(线程安全,同步方法)

优缺点说明:

1) 解决了线程不安全问题

2) 效率太低,每个线程在想获得类的实例的时候,执行getInstance()方法都要进行同步,而其实这个方法只执行一次实例化代码就可以了,后面的想获得该实例,直接return,方法进行同步效率太低

3) 结论:在实际开发中,不推荐使用这种方式。

posted @ 2020-10-31 09:33  树树树  阅读(232)  评论(0)    收藏  举报