单例模式-线程安全懒汉式(同步代码块)

 1 /**
 2  * 单例模式-线程安全懒汉式(同步代码块)
 3  */
 4 public class SingletonTest05 {
 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  Singleton getInstance() {
32         if(instance == null) {
33             synchronized(Singleton.class) {
34                 instance = new Singleton();
35             }
36         }
37         return instance;
38     }
39 
40 }

懒汉式(线程安全,同步代码块)

优缺点说明:

1) 这种方式,本意是对懒汉式线程安全同步方法的改进,因为前面的同步方法(懒汉式线程安全同步方法)效率太低,改为同步产生实例化的代码块

2) 但是这种同步并不能起到线程同步的作用,和单例模式线程不安全懒汉式遇到的情况一样,加入一个线程进入了 if(instance == null) 判断语句块,另一个线程也通过了这个判断语句,这时便会产生多个实例。

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

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