DCL.java 850 B

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