Java高并发编程(三)---单例模式

线程安全的单例模式
  1. 不使用同步锁
1 public class Singleton {
2     private static Singleton sin=new Singleton();    ///直接初始化一个实例对象
3     private Singleton(){    ///private类型的构造函数,保证其他类对象不能直接new一个该对象的实例
4     }
5     public static Singleton getSin(){    ///该类唯一的一个public方法    
6         return sin;
7     }
8 }
  1. 使用同步方法
 1 public class Singleton {  
 2      private static Singleton instance;  
 3      private Singleton (){
 4          
 5      }   
 6      public static synchronized Singleton getInstance(){    //对获取实例的方法进行同步
 7        if (instance == null)     
 8          instance = new Singleton(); 
 9        return instance;
10      }
11  }  
  1. 使用双重同步锁
 1 public class Singleton {  
 2      private static Singleton instance;  
 3      private Singleton (){
 4      }   
 5      public static Singleton getInstance(){    //对获取实例的方法进行同步
 6        if (instance == null){
 7            synchronized(Singleton.class){
 8                if (instance == null)
 9                    instance = new Singleton(); 
10            }
11        }
12        return instance;
13      }
14      
15  }
  1. 使用内部类
 1 public class Singleton {  
 2      private Singleton (){
 3			System.out.println("single");
 4      }   
 5      private static class Inner {   
 6       	private static Singleton s = new Singleton();
 7      }
 8		
 9		public static Singleton getSingle() {
 10			return Inner.s;
 11	    }
 12	    public static void main(String[] args){
 13		     ...
 14		}
 15 }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值