Double Check Locking 双检查锁机制

方法保证了多线程并发下的线程安全性。
这里在声明变量时使用了volatile关键字来保证其线程间的可见性;在同步代码块中使用二次检查,以保证其不被重复实例化。集合其二者,这种实现方式既保证了其高效性,也保证了其线程安全性。

 1 package com.test;
 2 
 3 public class MyObject{
 4     volatile private static MyObject instance;
 5 
 6     private MyObject() {
 7     }
 8 
 9     public static MyObject getInstance() { // 对获取实例的方法进行同步
10         try {
11             if (instance == null) {
12                 synchronized (MyObject.class) {
13                     if (instance == null) {
14                         instance = new MyObject();
15                     }
16                 }
17                  System.out.println(instance);
18             }
19         } catch (Exception e) {
20             e.printStackTrace();
21         }
22         return instance;
23     }
24 }
View Code
原文地址:https://www.cnblogs.com/kongxianghao/p/6848399.html