1234567891011121314151617181920212223 |
- package creational.singleton;//双检锁/双重校验锁
- public class DCL {
- private volatile static DCL dcl;
- private DCL (){}
- public static DCL getInstance() {
- if (dcl == null) { // 双重校验:第一次校验
- // 判断对象是否以及实例化过,没有则进入加锁代码块,此处可能有多个线程同时进来,等待类对象锁
- synchronized (DCL.class) {
- // 获取类对象锁,其他线程在外等待,其他线程进来再次判断,如果对象实例化了,则不需要再实例化
- if (dcl == null) { // 双重校验:第二次校验
- dcl = new DCL();
- }
- }
- }
- return dcl;
- }
- public static void main(String[] args){
- System.out.println(DCL.getInstance());
- }
- }
|