线程安全的单例模式
- 不使用同步锁
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 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 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 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 }