zoukankan      html  css  js  c++  java
  • 多线程下的单例

    1多线程安全单例模式一(不使用同步锁).

    复制代码
     1  1 public class Singleton {
     2  2     private Singleton()
     3  3     {}
     4  4     private static Singleton singleton;
     5  5     
     6  6     public static Singleton getInstance()
     7  7     {
     8  8         if(singleton ==null)
     9  9         {
    10 10             singleton =new Singleton();
    11 11         }
    12 12         return singleton;
    13 13     }
    14 14     
    15 15 
    16 16 }View Code
    复制代码

    2.多线程安全单例模式一(使用同步锁).

    复制代码
    public class Singleton {
        private Singleton()
        {}
        private static Singleton singleton;
        //sychronized 同步
        public static synchronized Singleton getInstance()
        {
            if(singleton ==null)
            {
                singleton =new Singleton();
            }
            return singleton;
        }
        
    
    }
    复制代码

    3.多线程安全单例模式一(使用双重同步锁).

    复制代码
    public class Singleton {  
         private static Singleton instance;  
         private Singleton (){
         }   
         public static Singleton getInstance(){    //对获取实例的方法进行同步
           if (instance == null){
               synchronized(Singleton.class){
                   if (instance == null)
                       instance = new Singleton(); 
               }
           }
           return instance;
         }
         
     }
  • 相关阅读:
    sql增删改查-转载
    委托和事件 链接
    三层架构-转载
    ToList()方法
    Invoke--转载
    C# 6.0新特性---语法糖
    索引器
    HBase学习总结(1)
    教程-关于Owner和Parent的区别
    问题-在TreeView使用时,发现选中的树节点会闪烁或消失
  • 原文地址:https://www.cnblogs.com/6zhi/p/5534764.html
Copyright © 2011-2022 走看看