zoukankan      html  css  js  c++  java
  • java单例模式之懒汉式分析

    转自:http://blog.csdn.net/withiter/article/details/8140338

    今天中午闲着没事,就随便写点关于Java单例模式的。其实单例模式实现有很多方法,这里我将对这些方法进行对比分析:

    第一种:

    [java] view plain copy
     
     print?
    1. public class Singleton2 {  
    2.       
    3.     private Singleton2(){  
    4.         System.out.println("This is Singleton2's instance.");  
    5.     };  
    6.       
    7.     private static Singleton2 instance = null;  
    8.       
    9.     public static Singleton2 getInstance(){  
    10.         if(instance == null) {  
    11.             instance = new Singleton2();  
    12.         }  
    13.         return instance;  
    14.     }  
    15. }  


    这种情况未加锁,可能会产生数据错误,比如两个同时新生成的对象,一个把对象数据改变了,而另一个使用的没改变之前的。

    第二种:

    [java] view plain copy
     
     print?
    1. public class Singleton1 {  
    2.       
    3.     private Singleton1(){  
    4.         System.out.println("This is Singleton1's instance.");  
    5.     }  
    6.       
    7.     private static Singleton1 instance = null;  
    8.   
    9.     public static Singleton1 getInstance2() {  
    10.         if(instance == null){   //1  
    11.             synchronized (Singleton1.class) {  //2  
    12.                 if(instance == null) {  
    13.                     instance = new Singleton1();  
    14.                 }  
    15.             }  
    16.         }  
    17.         return instance;  
    18.     }  
    19.       
    20. }  


    这种只会在第一次的时候产生阻塞,之后每实例一次对象,就会在第1步时跳过去,在第一次实例的时候,会在第2步那里产生阻塞,以后就不会了,这种相对来说是最好的。

    第三种:

    [java] view plain copy
     
     print?
    1. public class Singleton1 {  
    2.       
    3.     private Singleton1(){  
    4.         System.out.println("This is Singleton1's instance.");  
    5.     }  
    6.       
    7.     private static Singleton1 instance = null;  
    8.       
    9.     public static synchronized Singleton1 getInstance(){  //1  
    10.           
    11.         if(instance == null){  
    12.             instance = new Singleton1();  
    13.         }  
    14.         return instance;  
    15.     }  
    16. }  


    多线程的时候每次都会在1这里产生阻塞。

  • 相关阅读:
    洛谷 P2144 [FJOI2007]轮状病毒
    矩阵树定理学习笔记
    洛谷 P3990 [SHOI2013]超级跳马 解题报告
    【模板】exBSGS/Spoj3105 Mod
    【bzoj4804】欧拉心算 解题报告
    洛谷 P3235 [HNOI2014]江南乐 解题报告
    洛谷 P4706 取石子 解题报告
    一些我不会证又记不住的结论...
    【BZOJ2281】【Sdoi2011】黑白棋 解题报告
    洛谷 P4279 [SHOI2008]小约翰的游戏 解题报告
  • 原文地址:https://www.cnblogs.com/hadoop-dev/p/6949932.html
Copyright © 2011-2022 走看看