标签:block logs zed instance bsp blog static one on()
第一种方式:通过synchronized解决,性能下降
1 package singleton; 2 3 public class Singleton { 4 private Singleton() { 5 } 6 7 private static Singleton instance ; 8 9 public static synchronized Singleton getInstance() { 10 if (instance == null) { 11 synchronized (instance) { 12 instance = new Singleton(); 13 } 14 } 15 return instance; 16 } 17 }
第二种方式:JVM加载这个类时马上创建唯一的单件,可能创建时负担太重而该单件未使用,造成浪费.
1 package singleton; 2 3 public class Singleton { 4 private Singleton() { 5 } 6 7 private static Singleton instance = new Singleton(); 8 9 public static Singleton getInstance() { 10 return instance; 11 } 12 }
第三种方式:双重检查加锁
1 package singleton; 2 3 public class Singleton { 4 private Singleton() { 5 } 6 7 /** 8 * volatile确保当instance被初始化成Singleton实例时,多个线程正确的处理instance变量 9 */ 10 private volatile static Singleton instance; 11 12 public static Singleton getInstance() { 13 if (instance != null) { 14 synchronized (Singleton.class) { 15 if (instance != null) { 16 instance = new Singleton(); 17 } 18 } 19 } 20 return instance; 21 } 22 }
标签:block logs zed instance bsp blog static one on()
原文地址:http://www.cnblogs.com/crazyhusky/p/6309074.html