单例模式(Singleton)定义:一个类只能有一个实例,且该类能自行创建这个实例的模式。

单例模式有三个特点:

1、单例类只有1个实例对象。

2、该单例对象必须由单例类自己创建。

3、单例类对外提供一个访问该唯一实例的全局访问点。

 

懒加载实现,线程安全:

 1 public class LazySingleton {
 2 
 3     private static volatile LazySingleton lazySingleton = null;
 4 
 5     private LazySingleton() {
 6 
 7     }
 8 
 9     public static synchronized LazySingleton getInstance() {
10         if (lazySingleton == null) {
11             lazySingleton = new LazySingleton();
12         }
13         return lazySingleton;
14     }
15 }

 

饥饿式实现,线程安全:

 1 public class HungrySingleton {
 2 
 3     private static final HungrySingleton instance = new HungrySingleton();
 4 
 5     private HungrySingleton() {
 6 
 7     }
 8 
 9     public static HungrySingleton getInstance() {
10         return instance;
11     }
12 }

 

调用方式:

 1 public class Client {
 2 
 3     public static void main(String[] args) {
 4         // TODO Auto-generated method stub
 5 
 6         LazySingleton l1 = LazySingleton.getInstance();
 7         LazySingleton l2 = LazySingleton.getInstance();
 8         System.out.println(l1 == l2);
 9 
10         HungrySingleton h1 = HungrySingleton.getInstance();
11         HungrySingleton h2 = HungrySingleton.getInstance();
12         System.out.println(h1 == h2);
13     }
14 
15 }

执行结果:

懒加载双重检查机制,线程安全:

 1 public class MultiThreadSingleton {
 2 
 3     private static volatile MultiThreadSingleton multiThreadsSingleton = null;
 4 
 5     private MultiThreadSingleton() {
 6         System.out.println("MultiThreadSingleton init");
 7     }
 8 
 9     public static MultiThreadSingleton getInstance() {
10         if (multiThreadsSingleton == null) {
11             synchronized (MultiThreadSingleton.class) {
12                 if (multiThreadsSingleton == null) {
13                     multiThreadsSingleton = new MultiThreadSingleton();
14                 }
15             }
16         }
17         return multiThreadsSingleton;
18     }
19 
20     public static void main(String[] args) {
21         // TODO Auto-generated method stub
22         for (int i = 0; i < 10; i++) {
23             new Thread(() -> {
24                 MultiThreadSingleton.getInstance();
25             }).start();
26         }
27 
28     }
29 }
posted on 2019-12-28 11:00  Sempron2800+  阅读(139)  评论(0编辑  收藏  举报