单例模式----懒汉式改成安全
1 package com.yhqtv.java1; 2 3 /* 4 * @author XMKJ yhqtv.com Email:yhqtv@qq.com 5 * @create 2020-04-29-12:46 6 * 7 */ 8 public class Test { 9 public static void main(String[] args) { 10 11 } 12 } 13 14 class Dog { 15 private Dog() { 16 17 } 18 19 private static Dog dog = null; 20 21 private static Dog getDog() { 22 // 方式一:效率稍差 23 // synchronized (Dog.class) { 24 // if (dog == null) { 25 // dog = new Dog(); 26 // 27 // } 28 // return dog; 29 // } 30 // 方式二:效率高 31 if (dog==null) { 32 synchronized (Dog.class) { 33 if (dog == null) { 34 dog = new Dog(); 35 36 } 37 38 } 39 } 40 return dog; 41 42 } 43 }
版权声明:本文为yhqtv-com原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。